package com.hzeport.bgs22emduty.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.stream.CollectorUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.common.utils.Md5Utils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hzeport.bgs22emduty.config.SystemConfig;
import com.hzeport.bgs22emduty.config.exception.HdcException;
import com.hzeport.bgs22emduty.config.login.LoginCompoentService;
import com.hzeport.bgs22emduty.config.login.UserInfoDetailVO;
import com.hzeport.bgs22emduty.dto.*;
import com.hzeport.bgs22emduty.dto.duty.BasePersonInfoInitVO;
import com.hzeport.bgs22emduty.dto.duty.DutyPersonInitDetailVO;
import com.hzeport.bgs22emduty.dto.duty.DutyPersonInitVO;
import com.hzeport.bgs22emduty.entity.*;
import com.hzeport.bgs22emduty.enums.*;
import com.hzeport.bgs22emduty.outbound.*;
import com.hzeport.bgs22emduty.util.DateUtil;
import com.hzeport.bgs22emduty.util.DutySortUtil;
import com.hzeport.bgs22emduty.util.GuavacacheUtils;
import com.hzeport.bgs22emduty.util.PersonCompareUtil;
import com.hzeport.bgs22emduty.vo.ScreenDutyNoticeList.SmsSendPersonVO;
import com.hzeport.bgs22emduty.vo.dudyScheduleSet.DudyScheduleInitVO;
import com.hzeport.bgs22emduty.vo.dudyScheduleSet.DudyScheduleListVO;
import com.hzeport.bgs22emduty.vo.dudyScheduleSet.DudyScheduleListZGCountVO;
import com.hzeport.bgs22emduty.vo.dudyScheduleSet.DudyScheduleListZGVO;
import com.hzeport.bgs22emduty.common.base.BaseResult;
import com.hzeport.bgs22emduty.common.base.BaseServiceImpl;
import com.hzeport.bgs22emduty.outbound.db.BaseDeptInfoRepositoryImpl;
import com.hzeport.bgs22emduty.service.BaseDeptInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.data.keyvalue.core.event.KeyValueEvent;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.math.BigInteger;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import javax.annotation.Resource;

/**
 * ${comments}
 *
 * @author code generator
 * @date 2022-12-02 11:21:59
 */
@Service
@Slf4j
public class BaseDeptInfoServiceImpl extends BaseServiceImpl<BaseDeptInfoRepositoryImpl, BaseDeptInfo> implements BaseDeptInfoService {

    @Resource
    private BaseDeptInfoRepository baseDeptInfoRepository;
    @Resource
    private BasePersonInfoRepository basePersonInfoRepository;
    @Resource
    private BaseDeptTypeRepository baseDeptTypeRepository;
    @Resource
    private DutyScheduleInfoRepository dutyScheduleInfoRepository;
    @Resource
    private DutyScheduleSetCustomRepository dutyScheduleSetCustomRepository;
    @Resource
    private ParamHolidaysRepository paramHolidaysRepository;
    @Resource
    private DutyScheduleSetCustomRecordRepository dutyScheduleSetCustomRecordRepository;
    @Resource
    private LoginCompoentService loginCompoentService;
    @Resource
    private SystemConfig systemConfig;
    @Resource
    private ParamDictionaryRepository paramDictionaryRepository;
    @Resource
    private GuavacacheUtils guavacacheUtils;
    @Resource
    private ScreenSubCustomRepository screenSubCustomRepository;
    @Resource
    private ScreenDutyMapsRepository screenDutyMapsRepository;
    @Resource
    private ParamScheduleSettingRepository paramScheduleSettingRepository;
    @Resource
    private DutyScheduleGroupRecordRepository dutyScheduleGroupRecordRepository;
    @Resource
    private BaseGroupInfoRepository baseGroupInfoRepository;
    @Resource
    private ParamGroupDutyRepository paramGroupDutyRepository;
    @Resource
    private DutySortUtil dutySortUtil;

    @Override
    public Object customsList(UserInfoDetailVO userInfoDetailVO) {
        List<BaseDeptType> baseDeptTypes = baseDeptTypeRepository.list(new LambdaQueryWrapper<BaseDeptType>()
                .notLike(BaseDeptType::getSupervisorname, "\\")
                .notLike(BaseDeptType::getSupervisorname, "/")
                .isNotNull(BaseDeptType::getThirdId));
        List<String> ids = baseDeptTypes.stream().map(BaseDeptType::getThirdId).collect(Collectors.toList());
        List<BaseDeptInfo> baseDeptInfos = baseDeptInfoRepository.list(new LambdaQueryWrapper<BaseDeptInfo>()
                .in(BaseDeptInfo::getId, ids));
        if (userInfoDetailVO.getRole() != null && userInfoDetailVO.getRole().contains("SYSTEM_ADMIN1")) {
            return baseDeptInfos;
        } else {
            baseDeptInfos = baseDeptInfos.stream().filter(i -> userInfoDetailVO.getCustomscode().equals(i.getId())).collect(Collectors.toList());
            return baseDeptInfos;
        }
    }

    @Override
    public Object deptSList(String customId) {
//        List<BaseDeptType> baseDeptTypes=baseDeptTypeRepository.list(new LambdaQueryWrapper<BaseDeptType>()
//                .notLike(BaseDeptType::getSupervisorname,"\\")
//                .notLike(BaseDeptType::getSupervisorname,"/")
//                .isNotNull(BaseDeptType::getThirdId));
        List<BaseDeptInfo> childern = new ArrayList<>();
        BaseDeptInfo baseDeptInfo = baseDeptInfoRepository.getById(customId);
        if (baseDeptInfo == null) {
            return null;
        }
        List<BaseDeptInfo> deptInfoList = guavacacheUtils.getDepts();
//        List<String> ids=baseDeptTypes.stream().map(BaseDeptType::getThirdId).collect(Collectors.toList());
        deptInfoList = deptInfoList.stream().filter(i -> i != null).collect(Collectors.toList());
        childern.add(baseDeptInfo);
        getChild(baseDeptInfo, childern, deptInfoList);
        return childern;
    }

    @Override
    public Object userInDept(String deptId) {
        BaseDeptInfo baseDeptInfo = baseDeptInfoRepository.getById(deptId);
        if (baseDeptInfo == null) {
            return null;
        }
        List<BaseDeptInfo> deptInfoList = guavacacheUtils.getDepts();
        List<BaseDeptInfo> childern = new ArrayList<>();
        childern.add(baseDeptInfo);
        getChild(baseDeptInfo, childern, deptInfoList);
        return basePersonInfoRepository.list(new LambdaQueryWrapper<BasePersonInfo>()
                .in(BasePersonInfo::getDeptId, childern.stream().map(i -> i.getId())));
    }

    public List<BasePersonInfo> userInDeptWith(List<BaseDeptType> baseDeptTypes, BaseDeptInfo baseDeptInfo, List<BaseDeptInfo> deptInfoList, List<BasePersonInfo> basePersonInfoALLs) {
//       guavacacheUtils.userInDeptWith(baseDeptTypes,baseDeptInfo,allDepts, basePersonInfoALLs)
        List<BaseDeptInfo> childern = new ArrayList<>();
//        List<String> ids=baseDeptTypes.stream().map(BaseDeptType::getThirdId).collect(Collectors.toList());
//        deptInfoList=deptInfoList.stream().filter(i->i!=null&&!ids.contains(i.getId())).collect(Collectors.toList());

        childern.add(baseDeptInfo);
        List<BaseDeptInfo> CJChildren = deptInfoList.stream().filter(i -> i.getParentid() != null && i.getParentid().equals(baseDeptInfo.getId())).collect(Collectors.toList());
        childern.addAll(CJChildren);
        if (!CollectionUtils.isEmpty(CJChildren)) {
            List<BaseDeptInfo> KJChildren = deptInfoList.stream().filter(i -> i.getParentid() != null && CJChildren.stream().map(BaseDeptInfo::getId).collect(Collectors.toList()).contains(i.getParentid())).collect(Collectors.toList());
            childern.addAll(KJChildren);
//            if (!CollectionUtils.isEmpty(KJChildren)) {
//                List<BaseDeptInfo> otherChildren = deptInfoList.stream().filter(i -> i.getParentid() != null &&KJChildren.stream().map(BaseDeptInfo::getId).collect(Collectors.toList()).contains(i.getParentid())).collect(Collectors.toList());
//                childern.addAll(otherChildren);
//            }
        }
        //        getChild(baseDeptInfo, childern, deptInfoList);
        if (CollectionUtils.isEmpty(childern)) {
            return new ArrayList<>();
        }
        return basePersonInfoALLs.stream().filter(j -> childern.stream().map(i -> i.getId()).collect(Collectors.toList()).contains(j.getDeptId())).collect(Collectors.toList());
    }

    public List<BasePersonInfo> getBasePersonInfos(String roleValue, UserInfoDetailVO userInfoDetailVO) {
        AccreditBeanReaderHelper helper = new AccreditBeanReaderHelper();
        List<BasePersonInfo> levelOneReceiver = null;
        if (roleUser != null && roleUser.length != 0) {
            levelOneReceiver = basePersonInfoRepository.list(
                    new LambdaQueryWrapper<BasePersonInfo>()
                            .in(BasePersonInfo::getUserGuid, Arrays.asList(roleUser).stream().map(UsersInRoles::getUser_guid).collect(Collectors.toList()))
            );
        }
        //判断筛选出属于本关区下的部门的人员
        List<BaseDeptInfo> baseDeptInfos = (List) deptSList(userInfoDetailVO.getCustomscode());
        List<String> deptIds = baseDeptInfos.stream().map(BaseDeptInfo::getId).collect(Collectors.toList());
        List<BasePersonInfo> smsPerson = null;
        if (!CollectionUtils.isEmpty(levelOneReceiver)) {
            smsPerson = levelOneReceiver.stream().filter(basePersonInfo -> deptIds.contains(basePersonInfo.getDeptId())).collect(Collectors.toList());
        }
        return smsPerson;
    }

    @Override
    public SmsSendPersonVO getPersonInfoTOSmsMessage(String type)  {
        UserInfoDetailVO userInfoDetailVO = loginCompoentService.getUserInfo();
        List<BasePersonInfo> basePersonInfos = new ArrayList<>();
        //MESSAGE_RECEIVER_KJ 科级
        List<BasePersonInfo> message_receiver_kj = getBasePersonInfos("MESSAGE_RECEIVER_KJ", userInfoDetailVO);
//        log.info("message_receiver_kj:"+message_receiver_kj!=null?message_receiver_kj.size():"0");
        //MESSAGE_RECEIVER_CJ 处级
        List<BasePersonInfo> message_receiver_cj = getBasePersonInfos("MESSAGE_RECEIVER_CJ", userInfoDetailVO);
//        log.info("message_receiver_cj:"+message_receiver_cj.size());
        //MESSAGE_RECEIVER_GLD 关领导
        List<BasePersonInfo> message_receiver_gld = getBasePersonInfos("MESSAGE_RECEIVER_GLD", userInfoDetailVO);
//        log.info("message_receiver_gld:"+message_receiver_gld.size());
        /**
         * 总关：黄灯(0)、红灯(1)均发送值班员、值班员所在处室综合科科长、总值班室
         * 隶属关：黄灯发送隶属海关办公室主任，红灯发给隶属海关分管关领导
         * 钱江海关：红灯发办公室副主任、办公室主任
         */
        if (!CollectionUtils.isEmpty(message_receiver_kj)) {
            basePersonInfos.addAll(message_receiver_kj);
        }
        if (!CollectionUtils.isEmpty(message_receiver_cj)) {
            basePersonInfos.addAll(message_receiver_cj);
        }
        if (!CollectionUtils.isEmpty(message_receiver_gld)) {
            basePersonInfos.addAll(message_receiver_gld);
        }
        List<SmsPersonDTO> collect = basePersonInfos.stream().map(basePersonInfo -> {
            SmsPersonDTO smsPersonDTO = new SmsPersonDTO();
            smsPersonDTO.setId(basePersonInfo.getId());
            smsPersonDTO.setName(basePersonInfo.getUsername());
            return smsPersonDTO;
        }).collect(Collectors.toList());
        SmsSendPersonVO smsSendPersonVO = new SmsSendPersonVO();
        List<String> nameAndNos = basePersonInfos.stream().map(basePersonInfo -> basePersonInfo.getUsername() + "(" + basePersonInfo.getUserno() + ")").collect(Collectors.toList());
        smsSendPersonVO.setSmsSendName(nameAndNos);
        smsSendPersonVO.setSmsSendPerson(collect);
        return smsSendPersonVO;
    }

    @Override
    public List<BaseDeptInfo> selectdeptSList(String customId) {
//        List<BaseDeptType> baseDeptTypes = baseDeptTypeRepository.list(new LambdaQueryWrapper<BaseDeptType>()
//                .notLike(BaseDeptType::getSupervisorname, "\\")
//                .notLike(BaseDeptType::getSupervisorname, "/")
//                .isNotNull(BaseDeptType::getThirdId));
//        List<BaseDeptInfo> childern = new ArrayList<>();
//        BaseDeptInfo baseDeptInfo = baseDeptInfoRepository.getById(customId);
        List<BaseDeptInfo> deptInfoList = baseDeptInfoRepository.list(new LambdaQueryWrapper<BaseDeptInfo>()
                .eq(BaseDeptInfo::getCustomId, customId));
//        List<String> ids = baseDeptTypes.stream().map(BaseDeptType::getThirdId).collect(Collectors.toList());
//        deptInfoList = deptInfoList.stream().filter(i -> i != null && !ids.contains(i.getId())).collect(Collectors.toList());
////        childern.add(baseDeptInfo);
//        getChild(baseDeptInfo, childern, deptInfoList);
        return deptInfoList;
    }

    @Override
    public Object customsListWithOutPermission() {
        List<BaseDeptType> baseDeptTypes = baseDeptTypeRepository.list(new LambdaQueryWrapper<BaseDeptType>()
                .notLike(BaseDeptType::getSupervisorname, "\\")
                .notLike(BaseDeptType::getSupervisorname, "/")
                .isNotNull(BaseDeptType::getThirdId));
        List<String> ids = baseDeptTypes.stream().map(BaseDeptType::getThirdId).collect(Collectors.toList());
        List<BaseDeptInfo> baseDeptInfos = baseDeptInfoRepository.list(new LambdaQueryWrapper<BaseDeptInfo>()
                .in(BaseDeptInfo::getId, ids));
        return baseDeptInfos;
    }

    @Override
    public String getCustomIdByDeptId(String deptId) {
        ParamDictionary paramDictionary = paramDictionaryRepository.getOne(new LambdaQueryWrapper<ParamDictionary>()
                .eq(ParamDictionary::getParamModule, "ZBRY")
                .eq(ParamDictionary::getParamCode, "ZSGQ"), false);
        String customsString = paramDictionary.getParamName();
        String[] customArray = customsString.split(",");
        List<BaseDeptInfo> customs = baseDeptInfoRepository.list(new LambdaQueryWrapper<BaseDeptInfo>()
                .in(BaseDeptInfo::getDeptName, Arrays.asList(customArray)));
        customs = customs.stream().filter(distinctByKey(i -> i.getDeptName())).collect(Collectors.toList());
        List<BaseDeptInfo> alldepts = guavacacheUtils.getDepts();

        Map<String, BaseDeptInfo> baseDeptInfoMap = alldepts.stream().collect(Collectors.toMap(i -> i.getId(), i -> i));
        BaseDeptInfo baseDeptInfo = baseDeptInfoRepository.getById(deptId);
        return getCustom(baseDeptInfoMap, customs, baseDeptInfo);
    }

    static <T> Predicate<T> distinctByKey(Function<? super T, ?> ketExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        return t -> seen.putIfAbsent(ketExtractor.apply(t), Boolean.TRUE) == null;
    }

    @Override
    public Object neoCustomList(UserInfoDetailVO userInfoDetailVO) {
        List<ScreenMapsDto> screenMapsDtos = new ArrayList<>();
        List<ScreenDutyMaps> screenDutyMaps = new ArrayList<>();
        if (userInfoDetailVO.getRole() != null && !userInfoDetailVO.getRole().contains("ZGGLY")) {
            screenDutyMaps = screenDutyMapsRepository.list(new LambdaQueryWrapper<ScreenDutyMaps>()
                    .eq(ScreenDutyMaps::getCustomCode, userInfoDetailVO.getCustomscode()));
        } else {
            screenDutyMaps = screenDutyMapsRepository.list();
        }
        for (ScreenDutyMaps screenDutyMap : screenDutyMaps) {
            ScreenMapsDto screenMapsDto = new ScreenMapsDto();
            screenMapsDto.setId(screenDutyMap.getCustomCode());
            screenMapsDto.setDeptName(screenDutyMap.getCustomName());
            screenMapsDtos.add(screenMapsDto);
        }
        return screenMapsDtos;
//        BaseDeptInfo father=repository.getOne(new LambdaQueryWrapper<BaseDeptInfo>()
//        .isNull(BaseDeptInfo::getParentid));
//        List<BaseDeptInfo> children=repository.list(new LambdaQueryWrapper<BaseDeptInfo>()
//                .eq(BaseDeptInfo::getParentid,father.getId()));
//        if(userInfoDetailVO.getRole()!=null&&userInfoDetailVO.getRole().contains("ZGGLY")) {
//            return children;
//        }else{
//            children= children.stream().filter(i->i.getId().equals(userInfoDetailVO.getCustomscode())).collect(Collectors.toList());
//            return children;
//        }
//        List<BaseDeptInfo> children=repository.list(new LambdaQueryWrapper<BaseDeptInfo>()
//                .eq(BaseDeptInfo::getParentid,father.getId()));
//        return children;
    }

    @Override
    public Object subCustomsList(String customId) {
        return screenSubCustomRepository.list(new LambdaQueryWrapper<ScreenSubCustom>()
                .eq(ScreenSubCustom::getParentid, customId));
    }

    @Override
    public BaseResult deptTree(String customId) {

        return guavacacheUtils.deptTree(customId);
    }

    @Override
    public void setPubDepList(String id, List<String> pubDep) {
        BaseDeptInfo dept = repository.getById(id);
        BaseDeptInfo ssoDeptParent = repository.getById(dept.getParentid());
        if (ssoDeptParent != null) {
            setPubDepList(ssoDeptParent.getId(), pubDep);
        }
        pubDep.add(dept.getId());
    }

    @Override
    public Object customsListAll(UserInfoDetailVO userInfoDetailVO) {
        List<ScreenMapsDto> screenMapsDtos = new ArrayList<>();
        List<ScreenDutyMaps> screenDutyMaps = screenDutyMapsRepository.list();
        for (ScreenDutyMaps screenDutyMap : screenDutyMaps) {
            ScreenMapsDto screenMapsDto = new ScreenMapsDto();
            screenMapsDto.setId(screenDutyMap.getCustomCode());
            screenMapsDto.setDeptName(screenDutyMap.getCustomName());
            screenMapsDtos.add(screenMapsDto);
        }
        return screenMapsDtos;
    }

    @Override
    public List<DutyPersonInitDetailVO> dutyScheduleInitStep1(DudyScheduleInitVO dudyScheduleInitVO) throws Exception {
        /**
         * 获取历史记录
         * 拼装群组
         * 获取下一位，如果没有就获取第一位，回显
         */
        List<DutyScheduleGroupRecord> dutyScheduleGroupRecords;
        DutyScheduleSetCustom lastDutySetCustom = dutyScheduleSetCustomRepository.getOne(new LambdaQueryWrapper<DutyScheduleSetCustom>()
                .eq(DutyScheduleSetCustom::getCustomId, dudyScheduleInitVO.getCustomId())
                .orderByDesc(DutyScheduleSetCustom::getCreateTime), false);
        if (lastDutySetCustom == null) {
            dutyScheduleGroupRecords = new ArrayList<>();
        } else {
            dutyScheduleGroupRecords = dutyScheduleGroupRecordRepository.list(new LambdaQueryWrapper<DutyScheduleGroupRecord>()
                    .eq(DutyScheduleGroupRecord::getCustomId, dudyScheduleInitVO.getCustomId())
                    .eq(DutyScheduleGroupRecord::getSetCustomId, lastDutySetCustom.getId()));
            if (CollectionUtils.isEmpty(dutyScheduleGroupRecords)) {
                dutyScheduleGroupRecords = new ArrayList<>();
            }
        }

        List<String> setypes = SeTypeEnum.getAllSubCode();
        List<String> dutyTypes = SetDutyTypeEnum.getAllCode();
        List<DutyPersonInitDetailVO> dutyPersonInitDetailVOS = new ArrayList<>();
        for (String setype : setypes) {
            List<DutyPersonInitVO> dutyPersonInitVOS = new ArrayList<>();
            for (String dutyType : dutyTypes) {
                List<ParamGroupDuty> baseGroupInfos = paramGroupDutyRepository.list(new LambdaQueryWrapper<ParamGroupDuty>()
                        .eq(ParamGroupDuty::getCustomId, dudyScheduleInitVO.getCustomId())
                        .eq(ParamGroupDuty::getSeType, setype)
                        .eq(ParamGroupDuty::getSType, dutyType));
                if (CollectionUtils.isEmpty(baseGroupInfos)) {
                    DutyPersonInitVO dutyPersonInitVO = new DutyPersonInitVO();
                    dutyPersonInitVO.setDutyType(dutyType);
                    dutyPersonInitVO.setSeType(setype);
                    dutyPersonInitVO.setTypeName(SetDutyTypeEnum.getDescByCode(dutyType));
                    dutyPersonInitVOS.add(dutyPersonInitVO);
                    continue;
                }
                List<BasePersonInfo> persons = getPersonInCustomGroup(dudyScheduleInitVO.getCustomId(), setype, dutyType);
                persons.forEach(i -> i.setGlobalSort(i.getGlobalSort().replaceAll("[^0-9]", "")));
                if (CollectionUtils.isEmpty(persons)) {
                    throw new Exception("无法获取人员，请确认H4A配置中，以下值班群组是否为空群组或包括非本关区人员：" + SetDutyTypeEnum.getDescByCode(dutyType)+ SeTypeEnum.getDescByCode(setype) );
                }
                List<DutyScheduleGroupRecord> thisTypeRecord = dutyScheduleGroupRecords.stream().filter(i -> (setype.equals(i.getSeType()) &&
                        dutyType.equals(i.getDutyType())&&!StringUtil.isBlank(i.getFinalPersonNo())))
                        .collect(Collectors.toList());
                String startNum = "0";
                if (!CollectionUtils.isEmpty(thisTypeRecord)) {
                    startNum = thisTypeRecord.get(0).getFinalPersonSort();
                }
                if (startNum == null) {
                    startNum = "0";
                }
                BasePersonInfo startPerson = new BasePersonInfo();
                startPerson.setGlobalSort(startNum);

                List<BasePersonInfo> basePersonInfos = dutySortUtil.sortPerson(persons, baseGroupInfos);

                BasePersonInfo lastPerson = new BasePersonInfo();

                if (!CollectionUtils.isEmpty(thisTypeRecord)) {
                    for(int i = 0;i < basePersonInfos.size();i++){
                        BasePersonInfo basePersonInfo = basePersonInfos.get(i);
                        DutyScheduleGroupRecord dutyScheduleGroupRecord = thisTypeRecord.get(0);
                        if (basePersonInfo.getUserno().equals(dutyScheduleGroupRecord.getFinalPersonNo())){
                            if (i == basePersonInfos.size() -1){
                                lastPerson = basePersonInfos.get(0);
                            }else {
                                lastPerson = basePersonInfos.get(i+1);
                            }
                        }
                    }
                }else {
                    lastPerson = null;
                }

//                BasePersonInfo lastPerson = persons.stream().dropWhile(i -> PersonCompareUtil.comparePersonForSort().compare(i, startPerson) <= 0).min(PersonCompareUtil.comparePersonForSort())
//                        .orElse(null);
                if (lastPerson == null) {
                    lastPerson = basePersonInfos.get(0);
                }
                DutyPersonInitVO dutyPersonInitVO = new DutyPersonInitVO();
                dutyPersonInitVO.setDutyType(dutyType);
                dutyPersonInitVO.setSeType(setype);
                dutyPersonInitVO.setTypeName(SetDutyTypeEnum.getDescByCode(dutyType));
                dutyPersonInitVO.setPersonName(lastPerson.getUsername());
                dutyPersonInitVO.setPersonNo(lastPerson.getUserno());
                dutyPersonInitVO.setGlobalSort(lastPerson.getGlobalSort());
                dutyPersonInitVOS.add(dutyPersonInitVO);
            }
            DutyPersonInitDetailVO dutyPersonInitDetailVO = new DutyPersonInitDetailVO();
//            dutyPersonInitDetailVO.setDutyPersonInitVOS(dutyPersonInitDetailVO.getDutyPersonInitVOS());
            dutyPersonInitDetailVO.setSeType(setype);
            dutyPersonInitDetailVO.setDutyPersonInitVOS(dutyPersonInitVOS);
            dutyPersonInitDetailVOS.add(dutyPersonInitDetailVO);
        }
        return dutyPersonInitDetailVOS;
    }

    @Override
    public List<BasePersonInfoInitVO> dutyScheduleInitPerson(String customId, String seType) {
        List<String> dutyTypes = SetDutyTypeEnum.getAllCode();
        List<BasePersonInfoInitVO> basePersonInfoInitVOs = new ArrayList<>();
        for (String dutyType : dutyTypes) {
            BasePersonInfoInitVO basePersonInfoInitVO = new BasePersonInfoInitVO();
            List<BasePersonInfo> basePersonInfos = getPersonInCustomGroup(customId, seType, dutyType);
            Collections.sort(basePersonInfos, PersonCompareUtil.comparePersonForSort());
            List<BasePersonInfo> temp=JSONArray.parseArray(JSONArray.toJSONString(basePersonInfos),BasePersonInfo.class);
            basePersonInfoInitVO.setBasePersonInfoList(temp);
            basePersonInfoInitVO.setDutyType(dutyType);
            basePersonInfoInitVO.getBasePersonInfoList().forEach(i -> {
                if (!i.getUsername().contains("(")) {
                    i.setUsername(i.getUsername() + "(" + i.getUserno() + ")");
                }
            });
            basePersonInfoInitVOs.add(basePersonInfoInitVO);
        }
        return basePersonInfoInitVOs;
    }

    private List<BasePersonInfo> getPersonInCustomGroup(String customId, String type, String dutyType) {
        return basePersonInfoRepository.getPersonInCustomGroup(customId, type, dutyType);
    }

    @Override
    public List<String> getParentIds(String dDept, String customId) {
        BaseDeptInfo baseDeptInfo = baseDeptInfoRepository.getById(dDept);
        if (baseDeptInfo == null) {
            return Arrays.asList(dDept);
        }
        List<String> result = new ArrayList<>();
        result.add(dDept);
        result = getParent(result, baseDeptInfo, customId);
        return result;
    }

    private List<String> getParent(List<String> result, BaseDeptInfo baseDeptInfo, String customId) {
        if (baseDeptInfo.getId().equals(customId)) {
//             result.add(customId);
            return result;
        }
        BaseDeptInfo parent = baseDeptInfoRepository.getById(baseDeptInfo.getParentid());
        if (parent == null) {
            return result;
        }
        result.add(parent.getId());
        result = getParent(result, parent, customId);
        return result;
    }

    private BaseDeptInfoTreeDTO getTree(BaseDeptInfoTreeDTO rootNode, List<BaseDeptInfoTreeDTO> allParam, List<BaseDeptInfoTreeDTO> rootNodes) {

        List<BaseDeptInfoTreeDTO> children = allParam.stream().filter(i -> rootNode.getId().equals(i.getParentid())).collect(Collectors.toList());
        rootNode.setChildren(children);
        if (!CollectionUtils.isEmpty(children)) {
            for (BaseDeptInfoTreeDTO child : children) {
                child.setChildren(getTreeNode(child, allParam, children));
            }
        }
        return rootNode;
    }

    private List<BaseDeptInfoTreeDTO> getTreeNode(BaseDeptInfoTreeDTO rootNode, List<BaseDeptInfoTreeDTO> allParam, List<BaseDeptInfoTreeDTO> rootNodes) {
        List<BaseDeptInfoTreeDTO> children = allParam.stream().filter(i -> rootNode.getId().equals(i.getParentid())).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(children)) {
            for (BaseDeptInfoTreeDTO child : children) {
                child.setChildren(getTreeNode(child, allParam, children));
            }
        } else {
            children = null;
        }
        rootNode.setChildren(children);
        return children;
    }

    private String getCustom(Map<String, BaseDeptInfo> alldepts, List<BaseDeptInfo> customs, BaseDeptInfo baseDeptInfo) {
        if (customs.stream().map(BaseDeptInfo::getId).collect(Collectors.toList()).contains(baseDeptInfo.getId())) {
            return baseDeptInfo.getId();
        }
        BaseDeptInfo father = alldepts.get(baseDeptInfo.getParentid());
        if (father == null) {
            return "";
        }
        if (customs.stream().map(BaseDeptInfo::getId).collect(Collectors.toList()).contains(father.getId())) {
            return father.getId();
        }
        return getCustom(alldepts, customs, father);
    }


    @Override
    public Object userInCustoms(String customsId) throws Exception {
        List<BaseDeptInfo> deptInfoList = guavacacheUtils.getDepts();
        Map<String, BaseDeptInfo> deptInfoMap = deptInfoList.stream().collect(Collectors.toMap(i -> i.getId(), i -> i));
        BaseDeptInfo baseDeptInfo = deptInfoMap.get(customsId);
        if (baseDeptInfo == null) {
            return null;
        }
        List<BaseDeptType> baseDeptTypes = baseDeptTypeRepository.list(new LambdaQueryWrapper<BaseDeptType>()
                .notLike(BaseDeptType::getSupervisorname, "\\")
                .notLike(BaseDeptType::getSupervisorname, "/")
                .isNotNull(BaseDeptType::getThirdId));
        List<String> ids = baseDeptTypes.stream().map(BaseDeptType::getThirdId).collect(Collectors.toList());
        deptInfoList = deptInfoList.stream().filter(i -> i != null && !ids.contains(i.getId())).collect(Collectors.toList());
        List<BaseDeptInfo> childern = new ArrayList<>();
        childern.add(baseDeptInfo);
        getChild(baseDeptInfo, childern, deptInfoList);
        List<String> deptIds = childern.stream().map(BaseDeptInfo::getId).collect(Collectors.toList());
        return basePersonInfoRepository.list(new LambdaQueryWrapper<BasePersonInfo>()
                .in(BasePersonInfo::getDeptId, deptIds));
    }

    @Override
    public Object userWithPromission(String customsId, UserInfoDetailVO userInfoDetailVO, String userName) {
        List<BaseDeptInfo> deptInfoList = guavacacheUtils.getDepts();
        Map<String, BaseDeptInfo> deptInfoMap = deptInfoList.stream().collect(Collectors.toMap(i -> i.getId(), i -> i));
//        BaseDeptInfo baseDeptInfo = deptInfoMap.get(customsId);
//        if (userInfoDetailVO.getRole() != null && (userInfoDetailVO.getRole().contains("SCHEDULE_CJ_MGR"))) {
//            baseDeptInfo = deptInfoMap.get(userInfoDetailVO.getDeptId());
//        }
//        if (baseDeptInfo == null) {
//            return null;
//        }
////        List<BaseDeptType> baseDeptTypes = baseDeptTypeRepository.list(new LambdaQueryWrapper<BaseDeptType>()
////                .notLike(BaseDeptType::getSupervisorname, "\\")
////                .notLike(BaseDeptType::getSupervisorname, "/")
////                .isNotNull(BaseDeptType::getThirdId));
////        List<String> ids = baseDeptTypes.stream().map(BaseDeptType::getThirdId).collect(Collectors.toList());
////        deptInfoList = deptInfoList.stream().filter(i -> i != null && !ids.contains(i.getId())).collect(Collectors.toList());
//        List<BaseDeptInfo> childern = new ArrayList<>();
//        childern.add(baseDeptInfo);
//        getChild(baseDeptInfo, childern, deptInfoList);
//        List<String> deptIds = childern.stream().map(BaseDeptInfo::getId).collect(Collectors.toList());
        List<BasePersonInfo> basePersonInfos = basePersonInfoRepository.list(new LambdaQueryWrapper<BasePersonInfo>()
                .eq(BasePersonInfo::getCustomId, customsId)
                .like(!StringUtils.isEmpty(userName), BasePersonInfo::getUsername, userName)
        );
        basePersonInfos.forEach(i -> {
//            i.setFullPersonNameWithPersonId(i.getUsername() + "(" + i.getUserno() + ")");
            BaseDeptInfo baseDeptInfo = deptInfoMap.get(i.getDeptId());
            if (baseDeptInfo != null) {
                i.setFullPersonNameWithPersonId(i.getUsername() + "(" + i.getUserno() + ")" + "(" + (baseDeptInfo).getDeptName() + ")");
            } else {
                i.setFullPersonNameWithPersonId(i.getUsername() + "(" + i.getUserno() + ")" + "( )");
            }
        });
        return basePersonInfos;
    }

    @Override
    public DudyScheduleListZGVO dutyScheduleInitZS(DudyScheduleInitVO dudyScheduleInitVO) throws Exception {
        if (CollectionUtils.isEmpty(dudyScheduleInitVO.getSMonths())) {
            throw new Exception("初始化年份必传!");
        }
        if (StringUtils.isEmpty(dudyScheduleInitVO.getCustomId())) {
            throw new Exception("初始化关区编码必传!");
        }
        String dutyInitCustomName = systemConfig.getDutyInitCustomName();
        BaseDeptInfo baseDeptInfo = baseDeptInfoRepository.getOne(new LambdaQueryWrapper<BaseDeptInfo>()
                .eq(BaseDeptInfo::getDeptFullName, dutyInitCustomName));
        List<BaseDeptInfo> baseDeptInfos;
        if (baseDeptInfo != null && baseDeptInfo.getId() != null) {
            baseDeptInfos = baseDeptInfoRepository.list(new LambdaQueryWrapper<BaseDeptInfo>()
                    .eq(BaseDeptInfo::getParentid, baseDeptInfo.getId())
                    .orderByAsc(BaseDeptInfo::getGlobalSort));
        } else {
            baseDeptInfos = baseDeptInfoRepository.list(new LambdaQueryWrapper<BaseDeptInfo>()
                    .eq(BaseDeptInfo::getParentid, dudyScheduleInitVO.getCustomId())
                    .orderByAsc(BaseDeptInfo::getGlobalSort));
        }
        if (CollectionUtils.isEmpty(baseDeptInfos)) {
            throw new Exception("未能获取总署值班配置部门，请确认配置正确!");
        }
        List<ParamScheduleSetting> paramScheduleSettingListTYPE_RC = paramScheduleSettingRepository.list(new LambdaQueryWrapper<ParamScheduleSetting>()
                .eq(ParamScheduleSetting::getCustomId, dudyScheduleInitVO.getCustomId())
                .eq(ParamScheduleSetting::getDutyType, SetDutyTypeEnum.TYPE_RC.getValue()));
        List<ParamScheduleSetting> paramScheduleSettingListTYPE_ZMB = paramScheduleSettingRepository.list(new LambdaQueryWrapper<ParamScheduleSetting>()
                .eq(ParamScheduleSetting::getCustomId, dudyScheduleInitVO.getCustomId())
                .eq(ParamScheduleSetting::getDutyType, SetDutyTypeEnum.TYPE_ZMB.getValue()));
        List<ParamScheduleSetting> paramScheduleSettingListTYPE_ZYB = paramScheduleSettingRepository.list(new LambdaQueryWrapper<ParamScheduleSetting>()
                .eq(ParamScheduleSetting::getCustomId, dudyScheduleInitVO.getCustomId())
                .eq(ParamScheduleSetting::getDutyType, SetDutyTypeEnum.TYPE_ZYB.getValue()));
        List<ParamScheduleSetting> paramScheduleSettingListTYPE_ZM = paramScheduleSettingRepository.list(new LambdaQueryWrapper<ParamScheduleSetting>()
                .eq(ParamScheduleSetting::getCustomId, dudyScheduleInitVO.getCustomId())
                .eq(ParamScheduleSetting::getDutyType, SetDutyTypeEnum.TYPE_ZM.getValue()));
        if (CollectionUtils.isEmpty(paramScheduleSettingListTYPE_RC)) {
            throw new HdcException("工作日班未进行排班配置!");
        }
        if (CollectionUtils.isEmpty(paramScheduleSettingListTYPE_ZMB)) {
            throw new HdcException("节假日班未进行排班配置!");
        }
        if (CollectionUtils.isEmpty(paramScheduleSettingListTYPE_ZYB)) {
            throw new HdcException("重要班未进行排班配置!");
        }
        if (CollectionUtils.isEmpty(paramScheduleSettingListTYPE_ZM)) {
            throw new HdcException("周末班未进行排班配置!");
        }
        log.info("start" + LocalDateTime.now());
        String[] tempArray = dudyScheduleInitVO.getSMonths().get(0).split("-");
        Long startYear = Long.valueOf(tempArray[0]);
        Long startMonth = Long.valueOf(tempArray[1]);
        tempArray = dudyScheduleInitVO.getSMonths().get(1).split("-");
        Long endYear = Long.valueOf(tempArray[0]);
        Long endMonth = Long.valueOf(tempArray[1]);
        //todo
        //判断该时间是否已初始化过
        if (dutyScheduleSetCustomRepository.count(new LambdaQueryWrapper<DutyScheduleSetCustom>()
                .ge(DutyScheduleSetCustom::getSYearStart, startYear)
                .le(DutyScheduleSetCustom::getSYearEnd, startMonth)
                .ge(DutyScheduleSetCustom::getSMonthStart, endYear)
                .le(DutyScheduleSetCustom::getSMonthEnd, endMonth)) > 0) {
            throw new Exception("此关区的此时间有初始化记录不能再次初始化！");
        }
        DudyScheduleListZGVO dudyScheduleListVO = new DudyScheduleListZGVO();
        //获取该关区id下所有的部门.

        List<BaseDeptInfo> allDepts = baseDeptInfoRepository.list(new LambdaQueryWrapper<BaseDeptInfo>()
                .eq(BaseDeptInfo::getCustomId, dudyScheduleInitVO.getCustomId())
        );
        log.info("datas" + LocalDateTime.now());
        //工作日班下的部门列表和部门下的人员列表
        List<DutyPersonInitDetailVO> dutyPersonInitDetailVOS = new ArrayList<>();

        //获取本关区的历史记录
        log.info("records" + LocalDateTime.now());
        //计算本轮周期的所需人次
        if (endMonth < 12) {
            endMonth = endMonth + 1;
        } else {
            endMonth = 1l;
            endYear = endYear + 1;
        }
        List<ParamHolidays> holidays = paramHolidaysRepository.list(new LambdaQueryWrapper<ParamHolidays>()
                .ge(ParamHolidays::getHolidayDate, LocalDate.of((int) (long) startYear, (int) (long) startMonth, 1))
                .lt(ParamHolidays::getHolidayDate, LocalDate.of((int) (long) endYear, (int) (long) endMonth, 1))
                .eq(ParamHolidays::getHolidayType, HolidaysEnum.HOLIDAY.getValue())
                .eq(ParamHolidays::getCustomId, dudyScheduleInitVO.getCustomId()));//节假日天数
        List<ParamHolidays> importantDays = paramHolidaysRepository.list(new LambdaQueryWrapper<ParamHolidays>()
                .ge(ParamHolidays::getHolidayDate, LocalDate.of((int) (long) startYear, (int) (long) startMonth, 1))
                .lt(ParamHolidays::getHolidayDate, LocalDate.of((int) (long) endYear, (int) (long) endMonth, 1))
                .eq(ParamHolidays::getHolidayType, HolidaysEnum.IMPORTANT_PERIOD.getValue())
                .eq(ParamHolidays::getCustomId, dudyScheduleInitVO.getCustomId()));//重要时期天数
        List<ParamHolidays> hoildayExchanges = paramHolidaysRepository.list(new LambdaQueryWrapper<ParamHolidays>()
                .ge(ParamHolidays::getHolidayDate, LocalDate.of((int) (long) startYear, (int) (long) startMonth, 1))
                .lt(ParamHolidays::getHolidayDate, LocalDate.of((int) (long) endYear, (int) (long) endMonth, 1))
                .eq(ParamHolidays::getHolidayType, HolidaysEnum.HOLIDAY_EXCHANGE.getValue())
                .eq(ParamHolidays::getCustomId, dudyScheduleInitVO.getCustomId()));//节假日调班
        //24.08.02
        List<ParamScheduleSetting> rcSetting = paramScheduleSettingRepository.list(new LambdaQueryWrapper<ParamScheduleSetting>()
                .eq(ParamScheduleSetting::getCustomId, dudyScheduleInitVO.getCustomId())
                .eq(ParamScheduleSetting::getDutyType, SetDutyTypeEnum.TYPE_RC.getValue()));
        List<ParamScheduleSetting> zmbSetting = paramScheduleSettingRepository.list(new LambdaQueryWrapper<ParamScheduleSetting>()
                .eq(ParamScheduleSetting::getCustomId, dudyScheduleInitVO.getCustomId())
                .eq(ParamScheduleSetting::getDutyType, SetDutyTypeEnum.TYPE_ZMB.getValue()));
        List<ParamScheduleSetting> zybSetting = paramScheduleSettingRepository.list(new LambdaQueryWrapper<ParamScheduleSetting>()
                .eq(ParamScheduleSetting::getCustomId, dudyScheduleInitVO.getCustomId())
                .eq(ParamScheduleSetting::getDutyType, SetDutyTypeEnum.TYPE_ZYB.getValue()));
        List<ParamScheduleSetting> zmSetting = paramScheduleSettingRepository.list(new LambdaQueryWrapper<ParamScheduleSetting>()
                .eq(ParamScheduleSetting::getCustomId, dudyScheduleInitVO.getCustomId())
                .eq(ParamScheduleSetting::getDutyType, SetDutyTypeEnum.TYPE_ZM.getValue()));
        Integer hoilDayCount = holidays.size() * zmbSetting.size();//节假日 需要排班的轮次  节假日天数*节假日班次(上午/下午)
        Integer importantCount = importantDays.size() * zybSetting.size();//重要日 需要排班的轮次  重要日天数*重要日班次(上午/下午)
        Integer commonCount = DateUtil.getCommonCount(startYear, startMonth, endYear, endMonth, holidays, importantDays, hoildayExchanges, rcSetting, zmSetting);//日常班 需要排班的轮次(1-5 以及周末周六调班)
        Integer weekendCount = DateUtil.getWeekendCount(startYear, startMonth, endYear, endMonth, holidays, importantDays, hoildayExchanges, rcSetting, zmSetting);//周末班 需要排班的轮次(周末周六)
        List<ParamGroupDuty> paramGroupDuties = paramGroupDutyRepository.list(new LambdaQueryWrapper<ParamGroupDuty>()
                .eq(ParamGroupDuty::getCustomId, dudyScheduleInitVO.getCustomId()));//排班群组设置
        //工作日班
        List<BaseDeptInfo> hasGroupInfos = groupCheckInfo(dudyScheduleInitVO, paramGroupDuties, baseDeptInfos, allDepts);//当前排班的所有部门
        if (CollectionUtils.isEmpty(hasGroupInfos)) {
            throw new Exception("未能获取总署值班配置部门，请确认配置正确!");
        }
        List<DudyScheduleListZGVO.DudyTemplateZG> SdutyTemplate = createSTemplatesZG(paramGroupDuties, dudyScheduleInitVO, hasGroupInfos, allDepts, commonCount, "4", "1");//工作日下的署级
        List<DudyScheduleListZGVO.DudyTemplateZG> GdutyTemplate = createGTemplatesZG(paramGroupDuties, dudyScheduleInitVO, hasGroupInfos, allDepts, commonCount,    "5", "1");//工作日下的司级
        List<DudyScheduleListZGVO.DudyTemplateZG> CdutyTemplate = createCTemplatesZG(paramGroupDuties, dudyScheduleInitVO, hasGroupInfos, allDepts, commonCount, "6", "1");//工作日下的处级
        List<DudyScheduleListZGVO.DudyTemplateZG> KdutyTemplate = createMainTemplatesZG(paramGroupDuties, dudyScheduleInitVO, hasGroupInfos, allDepts, commonCount, "7", "1");//工作日下的主职
        List<DudyScheduleListZGVO.DudyTemplateZG> TdutyTemplate = createSubTemplatesZG(paramGroupDuties, dudyScheduleInitVO, hasGroupInfos, allDepts, commonCount, "8", "1");//工作日下的负值
        SdutyTemplate = mergeZGTemplate(SdutyTemplate, GdutyTemplate, CdutyTemplate, KdutyTemplate, TdutyTemplate, hasGroupInfos);
        DudyScheduleListZGVO.DailyDudy dailyDudy = new DudyScheduleListZGVO.DailyDudy();
        dailyDudy.setDudyTemplate(SdutyTemplate);
        dudyScheduleListVO.setDailyDudy(dailyDudy);

        SdutyTemplate = createSTemplatesZG(paramGroupDuties, dudyScheduleInitVO, hasGroupInfos, allDepts, weekendCount, "4", "4");
        GdutyTemplate = createGTemplatesZG(paramGroupDuties, dudyScheduleInitVO, hasGroupInfos, allDepts, weekendCount, "5", "4");
        CdutyTemplate = createCTemplatesZG(paramGroupDuties, dudyScheduleInitVO, hasGroupInfos, allDepts, weekendCount, "6", "4");
        KdutyTemplate = createMainTemplatesZG(paramGroupDuties, dudyScheduleInitVO, hasGroupInfos, allDepts, weekendCount, "7", "4");
        TdutyTemplate = createSubTemplatesZG(paramGroupDuties, dudyScheduleInitVO, hasGroupInfos, allDepts, weekendCount, "8", "4");
        SdutyTemplate = mergeZGTemplate(SdutyTemplate, GdutyTemplate, CdutyTemplate, KdutyTemplate, TdutyTemplate, hasGroupInfos);
        DudyScheduleListZGVO.DailyDudy weekend = new DudyScheduleListZGVO.DailyDudy();
        weekend.setDudyTemplate(SdutyTemplate);
        dudyScheduleListVO.setWeekendDudy(weekend);

        SdutyTemplate = createSTemplatesZG(paramGroupDuties, dudyScheduleInitVO, hasGroupInfos, allDepts, hoilDayCount, "4", "2");
        GdutyTemplate = createGTemplatesZG(paramGroupDuties, dudyScheduleInitVO, hasGroupInfos, allDepts, hoilDayCount, "5", "2");
        CdutyTemplate = createCTemplatesZG(paramGroupDuties, dudyScheduleInitVO, hasGroupInfos, allDepts, hoilDayCount, "6", "2");
        KdutyTemplate = createMainTemplatesZG(paramGroupDuties, dudyScheduleInitVO, hasGroupInfos, allDepts, hoilDayCount, "7", "2");
        TdutyTemplate = createSubTemplatesZG(paramGroupDuties, dudyScheduleInitVO, hasGroupInfos, allDepts, hoilDayCount, "8", "2");
        SdutyTemplate = mergeZGTemplate(SdutyTemplate, GdutyTemplate, CdutyTemplate, KdutyTemplate, TdutyTemplate, hasGroupInfos);
        DudyScheduleListZGVO.DailyDudy hoilDay = new DudyScheduleListZGVO.DailyDudy();
        hoilDay.setDudyTemplate(SdutyTemplate);
        dudyScheduleListVO.setHolidayAndVacationsDudy(hoilDay);


        SdutyTemplate = createSTemplatesZG(paramGroupDuties, dudyScheduleInitVO, hasGroupInfos, allDepts, importantCount, "4", "3");
        GdutyTemplate = createGTemplatesZG(paramGroupDuties, dudyScheduleInitVO, hasGroupInfos, allDepts, importantCount, "5", "3");
        CdutyTemplate = createCTemplatesZG(paramGroupDuties, dudyScheduleInitVO, hasGroupInfos, allDepts, importantCount, "6", "3");
        KdutyTemplate = createMainTemplatesZG(paramGroupDuties, dudyScheduleInitVO, hasGroupInfos, allDepts, importantCount, "7", "3");
        TdutyTemplate = createSubTemplatesZG(paramGroupDuties, dudyScheduleInitVO, hasGroupInfos, allDepts, importantCount, "8", "3");
        SdutyTemplate = mergeZGTemplate(SdutyTemplate, GdutyTemplate, CdutyTemplate, KdutyTemplate, TdutyTemplate, hasGroupInfos);
        DudyScheduleListZGVO.DailyDudy important = new DudyScheduleListZGVO.DailyDudy();
        important.setDudyTemplate(SdutyTemplate);
        dudyScheduleListVO.setImportantDayDudy(important);


        log.info("results" + LocalDateTime.now());
        return dudyScheduleListVO;
    }

    @Override
    public BaseResult deptTreeZS(String customId) {
        String dutyInitCustomName = systemConfig.getDutyInitCustomName();
        BaseDeptInfo baseDeptInfo = baseDeptInfoRepository.getOne(new LambdaQueryWrapper<BaseDeptInfo>()
                .eq(BaseDeptInfo::getDeptFullName, dutyInitCustomName));
        List<BaseDeptInfo> baseDeptInfos;
        if (baseDeptInfo != null && baseDeptInfo.getId() != null) {
            return deptTree(baseDeptInfo.getId());
        } else {
            return deptTree(customId);
        }

    }

    private List<DudyScheduleListZGVO.DudyTemplateZG> mergeZGTemplate(List<DudyScheduleListZGVO.DudyTemplateZG> sdutyTemplate, List<DudyScheduleListZGVO.DudyTemplateZG> gdutyTemplate, List<DudyScheduleListZGVO.DudyTemplateZG> cdutyTemplate, List<DudyScheduleListZGVO.DudyTemplateZG> kdutyTemplate, List<DudyScheduleListZGVO.DudyTemplateZG> tdutyTemplate, List<BaseDeptInfo> baseDeptInfos) {
        List<DudyScheduleListZGVO.DudyTemplateZG> deptTemplates = new ArrayList<>();
        for (BaseDeptInfo i : baseDeptInfos) {
            DudyScheduleListZGVO.DudyTemplateZG dudyTemplate = new DudyScheduleListZGVO.DudyTemplateZG();
            dudyTemplate.setDudyDeptId(i.getId());
            dudyTemplate.setDudyDept(i.getDeptName());
            dudyTemplate.setSort(i.getGlobalSort());
            deptTemplates.add(dudyTemplate);
        }
        if (!CollectionUtils.isEmpty(sdutyTemplate)) {
            for (int i = 0; i < deptTemplates.size(); i++) {
                deptTemplates.get(i).setSLeaderCount(sdutyTemplate.get(i).getSLeaderCount());
            }
        } else {
            for (int i = 0; i < deptTemplates.size(); i++) {
                deptTemplates.get(i).setSLeaderCount(0);
            }
        }
        if (!CollectionUtils.isEmpty(gdutyTemplate)) {
            for (int i = 0; i < deptTemplates.size(); i++) {
                deptTemplates.get(i).setGLeaderCount(gdutyTemplate.get(i).getGLeaderCount());
            }
        } else {
            for (int i = 0; i < deptTemplates.size(); i++) {
                deptTemplates.get(i).setGLeaderCount(0);
            }
        }
        if (!CollectionUtils.isEmpty(cdutyTemplate)) {
            for (int i = 0; i < deptTemplates.size(); i++) {
                deptTemplates.get(i).setCLeaderCount(cdutyTemplate.get(i).getCLeaderCount());
            }
        } else {
            for (int i = 0; i < deptTemplates.size(); i++) {
                deptTemplates.get(i).setCLeaderCount(0);
            }
        }
        if (!CollectionUtils.isEmpty(kdutyTemplate)) {
            for (int i = 0; i < deptTemplates.size(); i++) {
                deptTemplates.get(i).setMainDutyCount(kdutyTemplate.get(i).getMainDutyCount());
            }
        } else {
            for (int i = 0; i < deptTemplates.size(); i++) {
                deptTemplates.get(i).setMainDutyCount(0);
            }
        }
        if (!CollectionUtils.isEmpty(tdutyTemplate)) {
            for (int i = 0; i < deptTemplates.size(); i++) {
                deptTemplates.get(i).setSubDutyCount(tdutyTemplate.get(i).getSubDutyCount());
            }
        } else {
            for (int i = 0; i < deptTemplates.size(); i++) {
                deptTemplates.get(i).setSubDutyCount(0);
            }
        }
        return deptTemplates;
    }

    private List<DudyScheduleListZGVO.DudyTemplateZG> createGTemplatesZG(List<ParamGroupDuty> paramGroupDuties, DudyScheduleInitVO dudyScheduleInitVO, List<BaseDeptInfo> baseDeptInfos, List<BaseDeptInfo> allDepts, Integer commonCount, String seType, String dutyType) throws Exception {
        List<ParamGroupDuty> dailysDutys = paramGroupDuties.stream().filter(i -> seType.equals(i.getSeType()) && dutyType.equals(i.getSType()))
                .collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(dailysDutys)) {
            List<BasePersonInfo> persons = getPersonInCustomGroup(dudyScheduleInitVO.getCustomId(), seType, dutyType);
            persons.forEach(i -> i.setGlobalSort(i.getGlobalSort().replaceAll("[^0-9]", "")));
            persons = dutySortUtil.sortPerson(persons, dailysDutys);
            if (CollectionUtils.isEmpty(persons)) {
                throw new Exception("无法获取人员，请确认配置的值班群组是否为空群组" + seType + dutyType);
            }
            DutyPersonInitVO dutyPersonInitVO = dudyScheduleInitVO.getDutyPersonInitVOS().stream().filter(i -> dutyType.equals(i.getDutyType()) && seType.equals(i.getSeType())).findAny().orElse(null);
            List<DudyScheduleListZGVO.DudyTemplateZG> dutyTemplate = createGTemplateScountZG(persons, baseDeptInfos, allDepts, commonCount, dutyPersonInitVO);
            return dutyTemplate;
        } else {
            return null;
        }
    }

    private List<DudyScheduleListZGVO.DudyTemplateZG> createGTemplateScountZG(List<BasePersonInfo> persons, List<BaseDeptInfo> baseDeptInfos, List<BaseDeptInfo> allDepts, Integer commonCount, DutyPersonInitVO startPerson) {
        /**先把部门排序了
         //然后找到这个起点，从起点开始下排--->按部门排会更好
         **/
        //先把部门排序了
        DudyScheduleListZGVO.DudyTemplateZG startTemplate = null;
//        String startSort=startPerson.getGlobalSort();
//        persons=persons.stream().filter(j->new BigInteger(j.getGlobalSort()).compareTo(new BigInteger(startSort))>=0).collect(Collectors.toList());
        List<DudyScheduleListZGVO.DudyTemplateZG> deptTemplates = new ArrayList<>();
        for (BaseDeptInfo i : baseDeptInfos) {
            DudyScheduleListZGVO.DudyTemplateZG dudyTemplate = new DudyScheduleListZGVO.DudyTemplateZG();
            List<BasePersonInfo> thisDept = getBasePersonInfosInThisDept(persons, i, allDepts);
            dudyTemplate.setGLeaderCount(thisDept.size());
            dudyTemplate.setDudyDeptId(i.getId());
            dudyTemplate.setDudyDept(i.getDeptName());
            dudyTemplate.setSort(i.getGlobalSort());
            if (thisDept.stream().map(BasePersonInfo::getUserno).collect(Collectors.toList()).contains(startPerson.getPersonNo())) {
                startTemplate = dudyTemplate;
                int personIndex = 0;
                for (int j = 0; j < thisDept.size(); j++) {
                    BasePersonInfo basePersonInfo = thisDept.get(j);
                    if (basePersonInfo.getUserno().equals(startPerson.getPersonNo())) {
                        personIndex = j;
                    }
                }
                startTemplate.setGLeaderCount(thisDept.size() - personIndex);
            }
            deptTemplates.add(dudyTemplate);
        }
        if (startTemplate == null) {
            startTemplate = deptTemplates.get(0);
        }
        /**
         * 排序部门，顺便确定了起始部门，接下来，无线循环起始部门直到满员
         */
        List<DudyScheduleListZGVO.DudyTemplateZG> result
                = JSONArray.parseArray(JSONArray.toJSONString(deptTemplates), DudyScheduleListZGVO.DudyTemplateZG.class);
        Map<String, Integer> countMap = deptTemplates.stream().collect(Collectors.toMap(i -> i.getDudyDeptId(), i -> i.getGLeaderCount()));
        result.forEach(i -> i.setGLeaderCount(0));
        Integer nowCount = 0;
        Integer flag = 0;
        Integer round = 1;
        while (nowCount < commonCount) {
            if (flag >= result.size()) {
                flag = 0;
                round++;
            }
            DudyScheduleListZGVO.DudyTemplateZG nowDept = result.get(flag);
            if (round == 1 && nowCount == 0) {
                if (nowDept.getDudyDeptId().equals(startTemplate.getDudyDeptId())) {
                    if (nowCount + startTemplate.getGLeaderCount() < commonCount) {
                        nowCount += startTemplate.getGLeaderCount();
                        nowDept.setGLeaderCount(startTemplate.getGLeaderCount());
                        flag++;
                        continue;
                    } else if (nowCount + startTemplate.getGLeaderCount() == commonCount) {
                        nowCount += startTemplate.getGLeaderCount();
                        nowDept.setGLeaderCount(nowDept.getGLeaderCount() + startTemplate.getGLeaderCount());
                        break;
                    } else {
                        nowCount += commonCount;
                        nowDept.setGLeaderCount(commonCount);
                        break;
                    }
                } else {
                    flag++;
                    if (flag >= result.size()) {
                        flag = 0;
                        round++;
                    }
                    nowDept.setGLeaderCount(0);
                    continue;
                }
            }
            if (nowCount + countMap.get(nowDept.getDudyDeptId()) < commonCount) {
                nowCount += countMap.get(nowDept.getDudyDeptId());
                nowDept.setGLeaderCount(nowDept.getGLeaderCount() + countMap.get(nowDept.getDudyDeptId()));
                flag++;
            } else if (nowCount + countMap.get(nowDept.getDudyDeptId()) == commonCount) {
                nowCount += countMap.get(nowDept.getDudyDeptId());
                nowDept.setGLeaderCount(nowDept.getGLeaderCount() + countMap.get(nowDept.getDudyDeptId()));
                break;
            } else {
                Integer dif = commonCount - nowCount;
                if (round > 1) {
                    nowDept.setGLeaderCount(nowDept.getGLeaderCount() + dif);
                } else {
                    nowDept.setGLeaderCount(dif);
                }
                break;
            }
            if (flag >= result.size()) {
                flag = 0;
                round++;
            }
        }
        return result;
    }


    private List<DudyScheduleListZGVO.DudyTemplateZG> createCTemplatesZG(List<ParamGroupDuty> paramGroupDuties, DudyScheduleInitVO dudyScheduleInitVO, List<BaseDeptInfo> baseDeptInfos, List<BaseDeptInfo> allDepts, Integer commonCount, String seType, String dutyType) throws Exception {
        List<ParamGroupDuty> dailysDutys = paramGroupDuties.stream().filter(i -> seType.equals(i.getSeType()) && dutyType.equals(i.getSType()))
                .collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(dailysDutys)) {
            List<BasePersonInfo> persons = getPersonInCustomGroup(dudyScheduleInitVO.getCustomId(), seType, dutyType);
            persons.forEach(i -> i.setGlobalSort(i.getGlobalSort().replaceAll("[^0-9]", "")));
            persons = dutySortUtil.sortPerson(persons, dailysDutys);
            if (CollectionUtils.isEmpty(persons)) {
                throw new Exception("无法获取人员，请确认配置的值班群组是否为空群组" + seType + dutyType);
            }
            DutyPersonInitVO dutyPersonInitVO = dudyScheduleInitVO.getDutyPersonInitVOS().stream().filter(i -> dutyType.equals(i.getDutyType()) && seType.equals(i.getSeType())).findAny().orElse(null);
            List<DudyScheduleListZGVO.DudyTemplateZG> dutyTemplate = createCTemplateScountZG(persons, baseDeptInfos, allDepts, commonCount, dutyPersonInitVO);
            return dutyTemplate;
        } else {
            return null;
        }
    }

    private List<DudyScheduleListZGVO.DudyTemplateZG> createCTemplateScountZG(List<BasePersonInfo> persons, List<BaseDeptInfo> baseDeptInfos, List<BaseDeptInfo> allDepts, Integer commonCount, DutyPersonInitVO startPerson) {
        /**先把部门排序了
         //然后找到这个起点，从起点开始下排--->按部门排会更好
         **/
        //先把部门排序了
        DudyScheduleListZGVO.DudyTemplateZG startTemplate = null;
//        String startSort=startPerson.getGlobalSort();
//        persons=persons.stream().filter(j->new BigInteger(j.getGlobalSort()).compareTo(new BigInteger(startSort))>=0).collect(Collectors.toList());
        List<DudyScheduleListZGVO.DudyTemplateZG> deptTemplates = new ArrayList<>();
        for (BaseDeptInfo i : baseDeptInfos) {
            DudyScheduleListZGVO.DudyTemplateZG dudyTemplate = new DudyScheduleListZGVO.DudyTemplateZG();
            List<BasePersonInfo> thisDept = getBasePersonInfosInThisDept(persons, i, allDepts);
            dudyTemplate.setCLeaderCount(thisDept.size());
            dudyTemplate.setDudyDeptId(i.getId());
            dudyTemplate.setDudyDept(i.getDeptName());
            dudyTemplate.setSort(i.getGlobalSort());
            if (thisDept.stream().map(BasePersonInfo::getUserno).collect(Collectors.toList()).contains(startPerson.getPersonNo())) {
                startTemplate = dudyTemplate;
                int personIndex = 0;
                for (int j = 0; j < thisDept.size(); j++) {
                    BasePersonInfo basePersonInfo = thisDept.get(j);
                    if (basePersonInfo.getUserno().equals(startPerson.getPersonNo())) {
                        personIndex = j;
                    }
                }
                startTemplate.setCLeaderCount(thisDept.size() - personIndex);
            }
            deptTemplates.add(dudyTemplate);
        }
        if (startTemplate == null) {
            startTemplate = deptTemplates.get(0);
        }
        /**
         * 排序部门，顺便确定了起始部门，接下来，无线循环起始部门直到满员
         */
        List<DudyScheduleListZGVO.DudyTemplateZG> result
                = JSONArray.parseArray(JSONArray.toJSONString(deptTemplates), DudyScheduleListZGVO.DudyTemplateZG.class);
        Map<String, Integer> countMap = deptTemplates.stream().collect(Collectors.toMap(i -> i.getDudyDeptId(), i -> i.getCLeaderCount()));
        result.forEach(i -> i.setCLeaderCount(0));
        Integer nowCount = 0;
        Integer flag = 0;
        Integer round = 1;
        while (nowCount < commonCount) {
            if (flag >= result.size()) {
                flag = 0;
                round++;
            }
            DudyScheduleListZGVO.DudyTemplateZG nowDept = result.get(flag);
            if (round == 1 && nowCount == 0) {
                if (nowDept.getDudyDeptId().equals(startTemplate.getDudyDeptId())) {
                    if (nowCount + startTemplate.getCLeaderCount() < commonCount) {
                        nowCount += startTemplate.getCLeaderCount();
                        nowDept.setCLeaderCount(startTemplate.getCLeaderCount());
                        flag++;
                        continue;
                    } else if (nowCount + startTemplate.getCLeaderCount() == commonCount) {
                        nowCount += startTemplate.getCLeaderCount();
                        nowDept.setCLeaderCount(nowDept.getCLeaderCount() + startTemplate.getCLeaderCount());
                        break;
                    } else {
                        nowCount += commonCount;
                        nowDept.setCLeaderCount(commonCount);
                        break;
                    }
                } else {
                    flag++;
                    if (flag >= result.size()) {
                        flag = 0;
                        round++;
                    }
                    nowDept.setCLeaderCount(0);
                    continue;
                }
            }
            if (nowCount + countMap.get(nowDept.getDudyDeptId()) < commonCount) {
                nowCount += countMap.get(nowDept.getDudyDeptId());
                nowDept.setCLeaderCount(nowDept.getCLeaderCount() + countMap.get(nowDept.getDudyDeptId()));
                flag++;
            } else if (nowCount + countMap.get(nowDept.getDudyDeptId()) == commonCount) {
                nowCount += countMap.get(nowDept.getDudyDeptId());
                nowDept.setCLeaderCount(nowDept.getCLeaderCount() + countMap.get(nowDept.getDudyDeptId()));
                break;
            } else {
                Integer dif = commonCount - nowCount;
                if (round > 1) {
                    nowDept.setCLeaderCount(nowDept.getCLeaderCount() + dif);
                } else {
                    nowDept.setCLeaderCount(dif);
                }
                break;
            }
            if (flag >= result.size()) {
                flag = 0;
                round++;
            }
        }
        return result;
    }

    private List<DudyScheduleListZGVO.DudyTemplateZG> createMainTemplatesZG(List<ParamGroupDuty> paramGroupDuties, DudyScheduleInitVO dudyScheduleInitVO, List<BaseDeptInfo> baseDeptInfos, List<BaseDeptInfo> allDepts, Integer commonCount, String seType, String dutyType) throws Exception {
        List<ParamGroupDuty> dailysDutys = paramGroupDuties.stream().filter(i -> seType.equals(i.getSeType()) && dutyType.equals(i.getSType()))
                .collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(dailysDutys)) {
            List<BasePersonInfo> persons = getPersonInCustomGroup(dudyScheduleInitVO.getCustomId(), seType, dutyType);
            persons.forEach(i -> i.setGlobalSort(i.getGlobalSort().replaceAll("[^0-9]", "")));
            persons = dutySortUtil.sortPerson(persons, dailysDutys);
            if (CollectionUtils.isEmpty(persons)) {
                throw new Exception("无法获取人员，请确认配置的值班群组是否为空群组" + seType + dutyType);
            }
            DutyPersonInitVO dutyPersonInitVO = dudyScheduleInitVO.getDutyPersonInitVOS().stream().filter(i -> dutyType.equals(i.getDutyType()) && seType.equals(i.getSeType())).findAny().orElse(null);
            List<DudyScheduleListZGVO.DudyTemplateZG> dutyTemplate = createMainTemplateScountZG(persons, baseDeptInfos, allDepts, commonCount, dutyPersonInitVO);
            return dutyTemplate;
        } else {
            return null;
        }
    }

    private List<DudyScheduleListZGVO.DudyTemplateZG> createMainTemplateScountZG(List<BasePersonInfo> persons, List<BaseDeptInfo> baseDeptInfos, List<BaseDeptInfo> allDepts, Integer commonCount, DutyPersonInitVO startPerson) {
        /**先把部门排序了e
         //然后找到这个起点，从起点开始下排--->按部门排会更好
         **/
        //先把部门排序了
        DudyScheduleListZGVO.DudyTemplateZG startTemplate = null;
//        String startSort=startPerson.getGlobalSort();
//        persons=persons.stream().filter(j->new BigInteger(j.getGlobalSort()).compareTo(new BigInteger(startSort))>=0).collect(Collectors.toList());
        List<DudyScheduleListZGVO.DudyTemplateZG> deptTemplates = new ArrayList<>();
        for (BaseDeptInfo i : baseDeptInfos) {
            DudyScheduleListZGVO.DudyTemplateZG dudyTemplate = new DudyScheduleListZGVO.DudyTemplateZG();
            List<BasePersonInfo> thisDept = getBasePersonInfosInThisDept(persons, i, allDepts);
            dudyTemplate.setMainDutyCount(thisDept.size());
            dudyTemplate.setDudyDeptId(i.getId());
            dudyTemplate.setDudyDept(i.getDeptName());
            dudyTemplate.setSort(i.getGlobalSort());
            if (thisDept.stream().map(BasePersonInfo::getUserno).collect(Collectors.toList()).contains(startPerson.getPersonNo())) {
                startTemplate = dudyTemplate;
                int personIndex = 0;
                for (int j = 0; j < thisDept.size(); j++) {
                    BasePersonInfo basePersonInfo = thisDept.get(j);
                    if (basePersonInfo.getUserno().equals(startPerson.getPersonNo())) {
                        personIndex = j;
                    }
                }
                startTemplate.setMainDutyCount(thisDept.size() - personIndex);
            }
            deptTemplates.add(dudyTemplate);
        }
        if (startTemplate == null) {
            startTemplate = deptTemplates.get(0);
        }
        /**
         * 排序部门，顺便确定了起始部门，接下来，无线循环起始部门直到满员
         */
        List<DudyScheduleListZGVO.DudyTemplateZG> result
                = JSONArray.parseArray(JSONArray.toJSONString(deptTemplates), DudyScheduleListZGVO.DudyTemplateZG.class);
        Map<String, Integer> countMap = deptTemplates.stream().collect(Collectors.toMap(i -> i.getDudyDeptId(), i -> i.getMainDutyCount()));
        result.forEach(i -> i.setMainDutyCount(0));
        Integer nowCount = 0;
        Integer flag = 0;
        Integer round = 1;
        while (nowCount < commonCount) {
            if (flag >= result.size()) {
                flag = 0;
                round++;
            }
            DudyScheduleListZGVO.DudyTemplateZG nowDept = result.get(flag);
            if (round == 1 && nowCount == 0) {
                if (nowDept.getDudyDeptId().equals(startTemplate.getDudyDeptId())) {

                    if (startTemplate.getGLeaderCount() == null) {
                        startTemplate.setGLeaderCount(0);
                    }

                    if (nowCount + startTemplate.getMainDutyCount() < commonCount) {
                        nowCount += startTemplate.getMainDutyCount();
                        nowDept.setMainDutyCount(startTemplate.getMainDutyCount());
                        flag++;
                        continue;
                        // todo: startTemplate.getGLeaderCount()为空？怎么改
                    } else if (nowCount + startTemplate.getMainDutyCount() == commonCount) {
                        nowCount += startTemplate.getMainDutyCount();
                        nowDept.setMainDutyCount(nowDept.getMainDutyCount() + startTemplate.getMainDutyCount());
                        break;
                    } else {
                        nowCount += commonCount;
                        nowDept.setMainDutyCount(commonCount);
                        break;
                    }
                } else {
                    flag++;
                    if (flag >= result.size()) {
                        flag = 0;
                        round++;
                    }
                    nowDept.setMainDutyCount(0);
                    continue;
                }
            }
            if (nowCount + countMap.get(nowDept.getDudyDeptId()) < commonCount) {
                nowCount += countMap.get(nowDept.getDudyDeptId());
                nowDept.setMainDutyCount(nowDept.getMainDutyCount() + countMap.get(nowDept.getDudyDeptId()));
                flag++;
            } else if (nowCount + countMap.get(nowDept.getDudyDeptId()) == commonCount) {
                nowCount += countMap.get(nowDept.getDudyDeptId());
                nowDept.setMainDutyCount(nowDept.getMainDutyCount() + countMap.get(nowDept.getDudyDeptId()));
                break;
            } else {
                Integer dif = commonCount - nowCount;
                if (round > 1) {
                    nowDept.setMainDutyCount(nowDept.getMainDutyCount() + dif);
                } else {
                    nowDept.setMainDutyCount(dif);
                }
                break;
            }
            if (flag >= result.size()) {
                flag = 0;
                round++;
            }
        }
        return result;
    }

    private List<DudyScheduleListZGVO.DudyTemplateZG> createSubTemplatesZG(List<ParamGroupDuty> paramGroupDuties, DudyScheduleInitVO dudyScheduleInitVO, List<BaseDeptInfo> baseDeptInfos, List<BaseDeptInfo> allDepts, Integer commonCount, String seType, String dutyType) throws Exception {
        List<ParamGroupDuty> dailysDutys = paramGroupDuties.stream().filter(i -> seType.equals(i.getSeType()) && dutyType.equals(i.getSType()))
                .collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(dailysDutys)) {
            List<BasePersonInfo> persons = getPersonInCustomGroup(dudyScheduleInitVO.getCustomId(), seType, dutyType);
            persons.forEach(i -> i.setGlobalSort(i.getGlobalSort().replaceAll("[^0-9]", "")));
            persons = dutySortUtil.sortPerson(persons, dailysDutys);
            if (CollectionUtils.isEmpty(persons)) {
                throw new Exception("无法获取人员，请确认配置的值班群组是否为空群组" + seType + dutyType);
            }
            DutyPersonInitVO dutyPersonInitVO = dudyScheduleInitVO.getDutyPersonInitVOS().stream().filter(i -> dutyType.equals(i.getDutyType()) && seType.equals(i.getSeType())).findAny().orElse(null);
            List<DudyScheduleListZGVO.DudyTemplateZG> dutyTemplate = createSubTemplateScountZG(persons, baseDeptInfos, allDepts, commonCount, dutyPersonInitVO);
            return dutyTemplate;
        } else {
            return null;
        }
    }

    private List<DudyScheduleListZGVO.DudyTemplateZG> createSubTemplateScountZG(List<BasePersonInfo> persons, List<BaseDeptInfo> baseDeptInfos, List<BaseDeptInfo> allDepts, Integer commonCount, DutyPersonInitVO startPerson) {
        /**先把部门排序了
         //然后找到这个起点，从起点开始下排--->按部门排会更好
         **/
        //先把部门排序了
        DudyScheduleListZGVO.DudyTemplateZG startTemplate = null;
//        String startSort=startPerson.getGlobalSort();
//        persons=persons.stream().filter(j->new BigInteger(j.getGlobalSort()).compareTo(new BigInteger(startSort))>=0).collect(Collectors.toList());
        List<DudyScheduleListZGVO.DudyTemplateZG> deptTemplates = new ArrayList<>();
        for (BaseDeptInfo i : baseDeptInfos) {
            DudyScheduleListZGVO.DudyTemplateZG dudyTemplate = new DudyScheduleListZGVO.DudyTemplateZG();
            List<BasePersonInfo> thisDept = getBasePersonInfosInThisDept(persons, i, allDepts);
            dudyTemplate.setSubDutyCount(thisDept.size());
            dudyTemplate.setDudyDeptId(i.getId());
            dudyTemplate.setDudyDept(i.getDeptName());
            dudyTemplate.setSort(i.getGlobalSort());
            if (thisDept.stream().map(BasePersonInfo::getUserno).collect(Collectors.toList()).contains(startPerson.getPersonNo())) {
                startTemplate = dudyTemplate;
                int personIndex = 0;
                for (int j = 0; j < thisDept.size(); j++) {
                    BasePersonInfo basePersonInfo = thisDept.get(j);
                    if (basePersonInfo.getUserno().equals(startPerson.getPersonNo())) {
                        personIndex = j;
                    }
                }
                startTemplate.setSubDutyCount(thisDept.size() - personIndex);
            }
            deptTemplates.add(dudyTemplate);
        }
        if (startTemplate == null) {
            startTemplate = deptTemplates.get(0);
        }
        /**
         * 排序部门，顺便确定了起始部门，接下来，无线循环起始部门直到满员
         */
        List<DudyScheduleListZGVO.DudyTemplateZG> result
                = JSONArray.parseArray(JSONArray.toJSONString(deptTemplates), DudyScheduleListZGVO.DudyTemplateZG.class);
        Map<String, Integer> countMap = deptTemplates.stream().collect(Collectors.toMap(i -> i.getDudyDeptId(), i -> i.getSubDutyCount()));
        result.forEach(i -> i.setSubDutyCount(0));
        Integer nowCount = 0;
        Integer flag = 0;
        Integer round = 1;
        while (nowCount < commonCount) {
            if (flag >= result.size()) {
                flag = 0;
                round++;
            }
            DudyScheduleListZGVO.DudyTemplateZG nowDept = result.get(flag);
            if (round == 1 && nowCount == 0) {
                if (nowDept.getDudyDeptId().equals(startTemplate.getDudyDeptId())) {

                    if (startTemplate.getGLeaderCount() == null) {
                        startTemplate.setSubDutyCount(0);
                    }

                    if (nowCount + startTemplate.getSubDutyCount() < commonCount) {
                        nowCount += startTemplate.getSubDutyCount();
                        nowDept.setSubDutyCount(startTemplate.getSubDutyCount());
                        flag++;
                        continue;
                        // todo: startTemplate.getGLeaderCount()为空？怎么改
                    } else if (nowCount + startTemplate.getGLeaderCount() == commonCount) {
                        nowDept.setSubDutyCount(nowDept.getSubDutyCount() + startTemplate.getSubDutyCount());
                        break;
                    } else {
                        nowCount += commonCount;
                        nowDept.setSubDutyCount(commonCount);
                        break;
                    }
                } else {
                    flag++;
                    if (flag >= result.size()) {
                        flag = 0;
                        round++;
                    }
                    nowDept.setSubDutyCount(0);
                    continue;
                }
            }
            if (nowCount + countMap.get(nowDept.getDudyDeptId()) < commonCount) {
                nowCount += countMap.get(nowDept.getDudyDeptId());
                nowDept.setSubDutyCount(nowDept.getSubDutyCount() + countMap.get(nowDept.getDudyDeptId()));
                flag++;
            } else if (nowCount + countMap.get(nowDept.getDudyDeptId()) == commonCount) {
                nowCount += countMap.get(nowDept.getDudyDeptId());
                nowDept.setSubDutyCount(nowDept.getSubDutyCount() + countMap.get(nowDept.getDudyDeptId()));
                break;
            } else {
                Integer dif = commonCount - nowCount;
                if (round > 1) {
                    nowDept.setSubDutyCount(nowDept.getSubDutyCount() + dif);
                } else {
                    nowDept.setSubDutyCount(dif);
                }
                break;
            }
            if (flag >= result.size()) {
                flag = 0;
                round++;
            }
        }
        return result;
    }

    private List<DudyScheduleListZGVO.DudyTemplateZG> createSTemplatesZG(List<ParamGroupDuty> paramGroupDuties, DudyScheduleInitVO dudyScheduleInitVO, List<BaseDeptInfo> baseDeptInfos, List<BaseDeptInfo> allDepts, Integer commonCount, String seType, String dutyType) throws Exception {
        List<ParamGroupDuty> dailysDutys = paramGroupDuties.stream().filter(i -> seType.equals(i.getSeType()) && dutyType.equals(i.getSType()))
                .collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(dailysDutys)) {
            List<BasePersonInfo> persons = getPersonInCustomGroup(dudyScheduleInitVO.getCustomId(), seType, dutyType);
            persons.forEach(i -> i.setGlobalSort(i.getGlobalSort().replaceAll("[^0-9]", "")));
            persons = dutySortUtil.sortPerson(persons, dailysDutys);
            if (CollectionUtils.isEmpty(persons)) {
                throw new Exception("无法获取人员，请确认配置的值班群组是否为空群组" + seType + dutyType);
            }
            DutyPersonInitVO dutyPersonInitVO = dudyScheduleInitVO.getDutyPersonInitVOS().stream().filter(i -> dutyType.equals(i.getDutyType()) && seType.equals(i.getSeType())).findAny().orElse(null);
            List<DudyScheduleListZGVO.DudyTemplateZG> dutyTemplate = createTemplateScountZG(persons, baseDeptInfos, allDepts, commonCount, dutyPersonInitVO);
            return dutyTemplate;
        } else {
            return null;
        }
    }

    private List<DudyScheduleListZGVO.DudyTemplateZG> createTemplateScountZG(List<BasePersonInfo> persons, List<BaseDeptInfo> baseDeptInfos, List<BaseDeptInfo> allDepts, Integer commonCount, DutyPersonInitVO startPerson) {
        /**先把部门排序了
         //然后找到这个起点，从起点开始下排--->按部门排会更好
         **/
        //先把部门排序了
        DudyScheduleListZGVO.DudyTemplateZG startTemplate = null;
//        String startSort=startPerson.getGlobalSort();
//        persons=persons.stream().filter(j->new BigInteger(j.getGlobalSort()).compareTo(new BigInteger(startSort))>=0).collect(Collectors.toList());
        List<DudyScheduleListZGVO.DudyTemplateZG> deptTemplates = new ArrayList<>();
        for (BaseDeptInfo i : baseDeptInfos) {
            DudyScheduleListZGVO.DudyTemplateZG dudyTemplate = new DudyScheduleListZGVO.DudyTemplateZG();
            List<BasePersonInfo> thisDept = getBasePersonInfosInThisDept(persons, i, allDepts);
            dudyTemplate.setSLeaderCount(thisDept.size());
            dudyTemplate.setDudyDeptId(i.getId());
            dudyTemplate.setDudyDept(i.getDeptName());
            dudyTemplate.setSort(i.getGlobalSort());
            if (thisDept.stream().map(BasePersonInfo::getUserno).collect(Collectors.toList()).contains(startPerson.getPersonNo())) {
                startTemplate = dudyTemplate;
                int personIndex = 0;
                for (int j = 0; j < thisDept.size(); j++) {
                    BasePersonInfo basePersonInfo = thisDept.get(j);
                    if (basePersonInfo.getUserno().equals(startPerson.getPersonNo())) {
                        personIndex = j;
                    }
                }
                startTemplate.setSLeaderCount(thisDept.size() - personIndex);
            }
            deptTemplates.add(dudyTemplate);
        }
        if (startTemplate == null) {
            startTemplate = deptTemplates.get(0);
        }
        /**
         * 排序部门，顺便确定了起始部门，接下来，无线循环起始部门直到满员
         */
        List<DudyScheduleListZGVO.DudyTemplateZG> result
                = JSONArray.parseArray(JSONArray.toJSONString(deptTemplates), DudyScheduleListZGVO.DudyTemplateZG.class);
        Map<String, Integer> countMap = deptTemplates.stream().collect(Collectors.toMap(i -> i.getDudyDeptId(), i -> i.getSLeaderCount()));
        result.forEach(i -> i.setSLeaderCount(0));
        Integer nowCount = 0;
        Integer flag = 0;
        Integer round = 1;
        while (nowCount < commonCount) {
            if (flag >= result.size()) {
                flag = 0;
                round++;
            }
            DudyScheduleListZGVO.DudyTemplateZG nowDept = result.get(flag);
            if (round == 1 && nowCount == 0) {
                if (nowDept.getDudyDeptId().equals(startTemplate.getDudyDeptId())) {
                    if (nowCount + startTemplate.getSLeaderCount() < commonCount) {
                        nowCount += startTemplate.getSLeaderCount();
                        nowDept.setSLeaderCount(startTemplate.getSLeaderCount());
                        flag++;
                        continue;
                    } else if (nowCount + startTemplate.getSLeaderCount() == commonCount) {
                        nowCount += startTemplate.getSLeaderCount();
                        nowDept.setSLeaderCount(nowDept.getSLeaderCount() + startTemplate.getSLeaderCount());
                        break;
                    } else {
                        nowCount += commonCount;
                        nowDept.setSLeaderCount(commonCount);
                        break;
                    }
                } else {
                    flag++;
                    if (flag >= result.size()) {
                        flag = 0;
                        round++;
                    }
                    nowDept.setSLeaderCount(0);
                    continue;
                }
            }
            if (nowCount + countMap.get(nowDept.getDudyDeptId()) < commonCount) {
                nowCount += countMap.get(nowDept.getDudyDeptId());
                nowDept.setSLeaderCount(nowDept.getSLeaderCount() + countMap.get(nowDept.getDudyDeptId()));
                flag++;
            } else if (nowCount + countMap.get(nowDept.getDudyDeptId()) == commonCount) {
                nowDept.setSLeaderCount(nowDept.getSLeaderCount() + countMap.get(nowDept.getDudyDeptId()));
                break;
            } else {
                Integer dif = commonCount - nowCount;
                if (round > 1) {
                    nowDept.setSLeaderCount(nowDept.getSLeaderCount() + dif);
                } else {
                    nowDept.setSLeaderCount(dif);
                }
                break;
            }
            if (flag >= result.size()) {
                flag = 0;
                round++;
            }
        }
        return result;
    }

    private List<BaseDeptInfo> groupCheckInfo(DudyScheduleInitVO dudyScheduleInitVO, List<ParamGroupDuty> paramGroupDuties, List<BaseDeptInfo> deptInfos, List<BaseDeptInfo> allDepts) {
        List<BasePersonInfo> persons = basePersonInfoRepository.getPersonInCustomGroupForNoG(dudyScheduleInitVO.getCustomId(), null, null);
        List<BaseDeptInfo> result = new ArrayList<>();
        for (BaseDeptInfo i : deptInfos) {
            List<BasePersonInfo> thisDept = getBasePersonInfosInThisDept(persons, i, allDepts);
            if (!CollectionUtils.isEmpty(thisDept)) {
                result.add(i);
            }
        }
        return result;
    }

    private List<DudyScheduleListVO.DudyTemplate> mergeTemplate(List<DudyScheduleListVO.DudyTemplate> sTemplate, List<DudyScheduleListVO.DudyTemplate> dTemplate, List<BaseDeptInfo> baseDeptInfos) {
        if (sTemplate == null) {
            if (!CollectionUtils.isEmpty(dTemplate)) {
                for (int i = 0; i < dTemplate.size(); i++) {
                    dTemplate.get(i).setSectionLevelDudyNumber(0);
                    dTemplate.get(i).setRound(1);
                    dTemplate.get(i).setdRound(dTemplate.get(i).getRound());
                }
                return dTemplate;
            } else {
                List<DudyScheduleListVO.DudyTemplate> empty = baseDeptInfos.stream().map(i -> {
                    DudyScheduleListVO.DudyTemplate dudyTemplate = new DudyScheduleListVO.DudyTemplate();
                    dudyTemplate.setDivisionLevelDudyNumber(0);
                    dudyTemplate.setSectionLevelDudyNumber(0);
                    dudyTemplate.setRound(1);
                    return dudyTemplate;
                }).collect(Collectors.toList());
                return empty;
            }
        }
        if (dTemplate == null) {
            for (int i = 0; i < sTemplate.size(); i++) {
                sTemplate.get(i).setDivisionLevelDudyNumber(0);
                sTemplate.get(i).setdRound(1);
            }
            return sTemplate;
        }
        for (int i = 0; i < sTemplate.size(); i++) {
            sTemplate.get(i).setDivisionLevelDudyNumber(dTemplate.get(i).getDivisionLevelDudyNumber());
            sTemplate.get(i).setdRound(dTemplate.get(i).getRound());
        }
        return sTemplate;
    }

    private List<DudyScheduleListVO.DudyTemplate> createDTemplates(List<ParamGroupDuty> paramGroupDuties
            , DudyScheduleInitVO dudyScheduleInitVO, List<BaseDeptInfo> baseDeptInfos, List<BaseDeptInfo> allDepts, Integer commonCount, String seType, String dutyType) throws Exception {
        List<ParamGroupDuty> dailysDutys = paramGroupDuties.stream().filter(i -> seType.equals(i.getSeType()) && dutyType.equals(i.getSType()))
                .collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(dailysDutys)) {
            List<BasePersonInfo> persons = getPersonInCustomGroup(dudyScheduleInitVO.getCustomId(), seType, dutyType);
            persons.forEach(i -> i.setGlobalSort(i.getGlobalSort().replaceAll("[^0-9]", "")));
            if (CollectionUtils.isEmpty(persons)) {
                throw new Exception("无法获取人员，请确认配置的值班群组是否为空群组" + seType + dutyType);
            }
            persons = dutySortUtil.sortPerson(persons, dailysDutys);
            DutyPersonInitVO dutyPersonInitVO = dudyScheduleInitVO.getDutyPersonInitVOS().stream().filter(i -> dutyType.equals(i.getDutyType()) && seType.equals(i.getSeType())).findAny().orElse(null);
            List<DudyScheduleListVO.DudyTemplate> dutyTemplate = createTemplateDcount(persons, baseDeptInfos, allDepts, commonCount, dutyPersonInitVO);
            return dutyTemplate;
        } else {
            //do nothing
            return null;
//            throw new Exception("无法获取人员，请确认群组是否配置"+seType+dutyType);
        }
    }

    private List<DudyScheduleListVO.DudyTemplate> createSTemplates(List<ParamGroupDuty> paramGroupDuties
            , DudyScheduleInitVO dudyScheduleInitVO, List<BaseDeptInfo> baseDeptInfos, List<BaseDeptInfo> allDepts, Integer commonCount, String seType, String dutyType) throws Exception {
        List<ParamGroupDuty> dailysDutys = paramGroupDuties.stream().filter(i -> seType.equals(i.getSeType()) && dutyType.equals(i.getSType()))
                .collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(dailysDutys)) {
            List<BasePersonInfo> persons = getPersonInCustomGroup(dudyScheduleInitVO.getCustomId(), seType, dutyType);
            persons.forEach(i -> i.setGlobalSort(i.getGlobalSort().replaceAll("[^0-9]", "")));
            if (CollectionUtils.isEmpty(persons)) {
                throw new Exception("无法获取人员，请确认配置的值班群组是否为空群组" + seType + dutyType);
            }
            persons = dutySortUtil.sortPerson(persons, dailysDutys);
            DutyPersonInitVO dutyPersonInitVO = dudyScheduleInitVO.getDutyPersonInitVOS().stream().filter(i -> dutyType.equals(i.getDutyType()) && seType.equals(i.getSeType())).findAny().orElse(null);
            List<DudyScheduleListVO.DudyTemplate> dutyTemplate = createTemplateScount(persons, baseDeptInfos, allDepts, commonCount, dutyPersonInitVO);
            return dutyTemplate;
        } else {
            return null;
        }
    }

    private List<DudyScheduleListVO.DudyTemplate> createTemplateDcount(List<BasePersonInfo> persons, List<BaseDeptInfo> baseDeptInfos, List<BaseDeptInfo> allDepts, Integer commonCount, DutyPersonInitVO startPerson) {
        /**先把部门排序了
         //然后找到这个起点，从起点开始下排--->按部门排会更好
         **/
        //先把部门排序了
        DudyScheduleListVO.DudyTemplate startTemplate = null;
//        String startSort=startPerson.getGlobalSort();
//        persons=persons.stream().filter(j->new BigInteger(j.getGlobalSort()).compareTo(new BigInteger(startSort))>=0).collect(Collectors.toList());
        List<DudyScheduleListVO.DudyTemplate> deptTemplates = new ArrayList<>();
        for (BaseDeptInfo i : baseDeptInfos) {
            DudyScheduleListVO.DudyTemplate dudyTemplate = new DudyScheduleListVO.DudyTemplate();
            List<BasePersonInfo> thisDept = getBasePersonInfosInThisDept(persons, i, allDepts);
            dudyTemplate.setDivisionLevelDudyNumber(thisDept.size());
            dudyTemplate.setDudyDeptId(i.getId());
            dudyTemplate.setDudyDept(i.getDeptName());
            dudyTemplate.setSort(i.getGlobalSort());
            if (thisDept.stream().map(BasePersonInfo::getUserno).collect(Collectors.toList()).contains(startPerson.getPersonNo())) {
                startTemplate = dudyTemplate;
                int personIndex = 0;
                for (int j = 0; j < thisDept.size(); j++) {
                    BasePersonInfo basePersonInfo = thisDept.get(j);
                    if (basePersonInfo.getUserno().equals(startPerson.getPersonNo())) {
                        personIndex = j;
                    }
                }
                startTemplate.setDivisionLevelDudyNumber(thisDept.size() - personIndex);
            }
            deptTemplates.add(dudyTemplate);
        }
        if (startTemplate == null) {
            startTemplate = deptTemplates.get(0);
        }
        /**
         * 排序部门，顺便确定了起始部门，接下来，无线循环起始部门直到满员
         */
        List<DudyScheduleListVO.DudyTemplate> result
                = JSONArray.parseArray(JSONArray.toJSONString(deptTemplates), DudyScheduleListVO.DudyTemplate.class);
        Map<String, Integer> countMap = deptTemplates.stream().collect(Collectors.toMap(i -> i.getDudyDeptId(), i -> i.getDivisionLevelDudyNumber()));
        result.forEach(i -> i.setDivisionLevelDudyNumber(0));
        Integer nowCount = 0;
        Integer flag = 0;
        Integer round = 1;
        while (nowCount < commonCount) {
            if (flag >= result.size()) {
                flag = 0;
                round++;
            }
            DudyScheduleListVO.DudyTemplate nowDept = result.get(flag);
            if (round == 1 && nowCount == 0) {
                if (nowDept.getDudyDeptId().equals(startTemplate.getDudyDeptId())) {
                    if (nowCount + startTemplate.getDivisionLevelDudyNumber() < commonCount) {
                        nowCount += startTemplate.getDivisionLevelDudyNumber();
                        nowDept.setDivisionLevelDudyNumber(startTemplate.getDivisionLevelDudyNumber());
                        flag++;
                        continue;
                    } else if (nowCount + startTemplate.getDivisionLevelDudyNumber() == commonCount) {
                        nowDept.setDivisionLevelDudyNumber(nowDept.getDivisionLevelDudyNumber() + startTemplate.getDivisionLevelDudyNumber());
                        break;
                    } else {
                        nowCount += commonCount;
                        nowDept.setDivisionLevelDudyNumber(commonCount);
                        break;
                    }
                } else {
                    flag++;
                    if (flag >= result.size()) {
                        flag = 0;
                        round++;
                    }
                    nowDept.setDivisionLevelDudyNumber(0);
                    continue;
                }
            }
            if (nowCount + countMap.get(nowDept.getDudyDeptId()) < commonCount) {
                nowCount += countMap.get(nowDept.getDudyDeptId());
                nowDept.setDivisionLevelDudyNumber(nowDept.getDivisionLevelDudyNumber() + countMap.get(nowDept.getDudyDeptId()));
                nowDept.setRound(round);
                flag++;
            } else if (nowCount + countMap.get(nowDept.getDudyDeptId()) == commonCount) {
                nowCount += countMap.get(nowDept.getDudyDeptId());
                nowDept.setDivisionLevelDudyNumber(nowDept.getDivisionLevelDudyNumber() + countMap.get(nowDept.getDudyDeptId()));
                nowDept.setRound(round);
                break;
            } else {

                Integer dif = commonCount - nowCount;
                if (round > 1) {
                    nowDept.setDivisionLevelDudyNumber(nowDept.getDivisionLevelDudyNumber() + dif);
                } else {
                    nowDept.setDivisionLevelDudyNumber(dif);
                }
                nowDept.setRound(round);
                break;
            }
            if (flag >= result.size()) {
                flag = 0;
                round++;
            }
        }
        result.forEach(i -> {
            if (i.getRound() == null || i.getRound() == 0) {
                i.setRound(1);
            }
        });
        return result;
    }

    private List<DudyScheduleListVO.DudyTemplate> createTemplateScount(List<BasePersonInfo> persons, List<BaseDeptInfo> baseDeptInfos, List<BaseDeptInfo> allDepts, Integer commonCount, DutyPersonInitVO startPerson) {
        /**先把部门排序了
         //然后找到这个起点，从起点开始下排--->按部门排会更好
         **/
        //先把部门排序了
        DudyScheduleListVO.DudyTemplate startTemplate = null;
//        String startSort=startPerson.getGlobalSort();
//        persons=persons.stream().filter(j->new BigInteger(j.getGlobalSort()).compareTo(new BigInteger(startSort))>=0).collect(Collectors.toList());
        List<DudyScheduleListVO.DudyTemplate> deptTemplates = new ArrayList<>();
        for (BaseDeptInfo i : baseDeptInfos) {
            DudyScheduleListVO.DudyTemplate dudyTemplate = new DudyScheduleListVO.DudyTemplate();
            List<BasePersonInfo> thisDept = getBasePersonInfosInThisDept(persons, i, allDepts);
            dudyTemplate.setSectionLevelDudyNumber(thisDept.size());
            dudyTemplate.setDudyDeptId(i.getId());
            dudyTemplate.setDudyDept(i.getDeptName());
            dudyTemplate.setSort(i.getGlobalSort());
            if (thisDept.stream().map(BasePersonInfo::getUserno).collect(Collectors.toList()).contains(startPerson.getPersonNo())) {
                startTemplate = dudyTemplate;
                int personIndex = 0;
                for (int j = 0; j < thisDept.size(); j++) {
                    BasePersonInfo basePersonInfo = thisDept.get(j);
                    if (basePersonInfo.getUserno().equals(startPerson.getPersonNo())) {
                        personIndex = j;
                    }
                }
                startTemplate.setSectionLevelDudyNumber(thisDept.size() - personIndex);
            }
            deptTemplates.add(dudyTemplate);
        }
        if (startTemplate == null) {
            startTemplate = deptTemplates.get(0);
        }
        /**
         * 排序部门，顺便确定了起始部门，接下来，无线循环起始部门直到满员
         */
        List<DudyScheduleListVO.DudyTemplate> result
                = JSONArray.parseArray(JSONArray.toJSONString(deptTemplates), DudyScheduleListVO.DudyTemplate.class);
        Map<String, Integer> countMap = deptTemplates.stream().collect(Collectors.toMap(i -> i.getDudyDeptId(), i -> i.getSectionLevelDudyNumber()));
        result.forEach(i -> i.setSectionLevelDudyNumber(0));
        Integer nowCount = 0;
        Integer flag = 0;
        Integer round = 1;
        while (nowCount < commonCount) {
            if (flag >= result.size()) {
                flag = 0;
                round++;
            }
            DudyScheduleListVO.DudyTemplate nowDept = result.get(flag);
            if (round == 1 && nowCount == 0) {
                if (nowDept.getDudyDeptId().equals(startTemplate.getDudyDeptId())) {
                    if (nowCount + startTemplate.getSectionLevelDudyNumber() < commonCount) {
                        nowCount += startTemplate.getSectionLevelDudyNumber();
                        nowDept.setSectionLevelDudyNumber(startTemplate.getSectionLevelDudyNumber());
                        nowDept.setRound(round);
                        flag++;
                        continue;
                    } else if (nowCount + startTemplate.getSectionLevelDudyNumber() == commonCount) {
                        nowDept.setSectionLevelDudyNumber(nowDept.getSectionLevelDudyNumber() + startTemplate.getSectionLevelDudyNumber());
                        nowDept.setRound(round);
                        break;
                    } else {
                        nowCount += commonCount;
                        nowDept.setSectionLevelDudyNumber(commonCount);
                        nowDept.setRound(round);
                        break;
                    }
                } else {
                    flag++;
                    if (flag >= result.size()) {
                        flag = 0;
                        round++;
                    }
                    nowDept.setRound(1);
                    nowDept.setSectionLevelDudyNumber(0);
                    continue;
                }
            }

            if (nowCount + countMap.get(nowDept.getDudyDeptId()) < commonCount) {
                nowCount += countMap.get(nowDept.getDudyDeptId());
                nowDept.setSectionLevelDudyNumber(nowDept.getSectionLevelDudyNumber() + countMap.get(nowDept.getDudyDeptId()));
                nowDept.setRound(round);
                flag++;
            } else if (nowCount + countMap.get(nowDept.getDudyDeptId()) == commonCount) {
                nowCount += countMap.get(nowDept.getDudyDeptId());
                nowDept.setSectionLevelDudyNumber(nowDept.getSectionLevelDudyNumber() + countMap.get(nowDept.getDudyDeptId()));
                nowDept.setRound(round);
                break;
            } else {
                Integer dif = commonCount - nowCount;
                if (round > 1) {
                    nowDept.setSectionLevelDudyNumber(nowDept.getSectionLevelDudyNumber() + dif);
                } else {
                    nowDept.setSectionLevelDudyNumber(dif);
                }
                nowDept.setRound(round);
                break;
            }
            if (flag >= result.size()) {
                flag = 0;
                round++;
            }
        }
        result.forEach(i -> {
            if (i.getRound() == null || i.getRound() == 0) {
                i.setRound(1);
            }
        });
        return result;
    }

    public List<BasePersonInfo> getBasePersonInfosInThisDept(List<BasePersonInfo> persons, BaseDeptInfo baseDeptInfo, List<BaseDeptInfo> allDepts) {
        JSONObject temp = new JSONObject();
        temp.put("persons", persons);
        temp.put("baseDeptInfo", baseDeptInfo);
        String md5 = Md5Utils.getMD5(JSONObject.toJSONString(temp).getBytes());
        return guavacacheUtils.getBasePersonInfosInThisDept(md5, persons, baseDeptInfo, allDepts);

    }

    @Override
    public BasePersonInfoInitVO dutyScheduleInitPersonForDetail(String customId, String seType, String dutyType) throws Exception {
        switch (dutyType) {
            case "科员":
            case "科领导":
                dutyType = "3";
                break;
            case "处领导":
                dutyType = "2";
                break;
            case "关领导":
                dutyType = "1";
                break;
        }
        BasePersonInfoInitVO basePersonInfoInitVO = new BasePersonInfoInitVO();
        basePersonInfoInitVO.setBasePersonInfoList(getPersonInCustomGroup(customId, dutyType, seType));
        if (CollectionUtils.isEmpty(basePersonInfoInitVO.getBasePersonInfoList())) {
            throw new Exception("本关区的此群组下没有人员" + SetDutyTypeEnum.getDescByCode(seType) + "|" + SeTypeEnum.getDescByCode(dutyType));
        }
        basePersonInfoInitVO.setDutyType(dutyType);
        List<BaseDeptInfo> baseDeptInfos = guavacacheUtils.getDepts();
        Map<String, BaseDeptInfo> baseDeptInfoMap = baseDeptInfos.stream().collect(Collectors.toMap(i -> i.getId(), i -> i));
        basePersonInfoInitVO.getBasePersonInfoList().forEach(i -> {
            BaseDeptInfo baseDeptInfo = baseDeptInfoMap.get(i.getDeptId());
            if (baseDeptInfo != null) {
                String deptName = baseDeptInfo.getDeptName() != null ? "(" + baseDeptInfo.getDeptName() + ")" : "";
                if (!i.getUsername().contains("(")) {
                    i.setFullPersonNameWithPersonId(i.getUsername() + "(" + i.getUserno() + ")" + deptName);
                } else {
                    i.setFullPersonNameWithPersonId(i.getUsername() + deptName);
                }
            } else {
                i.setFullPersonNameWithPersonId(i.getUsername() + "(" + i.getUserno() + ")");
            }
        });
        return basePersonInfoInitVO;
    }

    @Override
    public List<BasePersonInfoInitVO> dutyScheduleInitPersonZS(String type) {
        UserInfoDetailVO userInfoDetailVO = loginCompoentService.getUserInfo();
        List<String> dutyTypes = SetDutyTypeEnum.getAllCode();
        List<String> seTypes;
        if ("1".equals(type)) {
            seTypes = SeTypeEnum.getAdminLeaderCode();
        } else {
            seTypes = SeTypeEnum.getAdminWorkerCode();
        }

        List<BasePersonInfoInitVO> basePersonInfoInitVOs = new ArrayList<>();
        for (String dutyType : dutyTypes) {
            for (String seType : seTypes) {
                BasePersonInfoInitVO basePersonInfoInitVO = new BasePersonInfoInitVO();
                List<BasePersonInfo> basePersonInfos=getPersonInCustomGroup(userInfoDetailVO.getCustomscode(), seType, dutyType);
                Collections.sort(basePersonInfos, PersonCompareUtil.comparePersonForSort());
                List<BasePersonInfo> temp=JSONArray.parseArray(JSONArray.toJSONString(basePersonInfos),BasePersonInfo.class);
                basePersonInfoInitVO.setBasePersonInfoList(temp);
                basePersonInfoInitVO.setDutyType(dutyType);
                basePersonInfoInitVO.setDutyTypeName(SetDutyTypeEnum.getDescByCode(dutyType));
                basePersonInfoInitVO.setSeType(dutyType);
                basePersonInfoInitVO.setSeTypeName(SeTypeEnum.getDescByCode(dutyType));
                basePersonInfoInitVO.getBasePersonInfoList().forEach(i -> {
                    if (!i.getUsername().contains("(")) {
                        i.setUsername(i.getUsername() + "(" + i.getUserno() + ")");
                    }
                });
                basePersonInfoInitVOs.add(basePersonInfoInitVO);
            }
        }
        return basePersonInfoInitVOs;
    }

    @Override
    public List<DutyPersonInitDetailVO> dutyScheduleInitStep1ZS(DudyScheduleInitVO dudyScheduleInitVO) throws Exception {
        /**
         * 获取历史记录
         * 拼装群组
         * 获取下一位，如果没有就获取第一位，回显
         */
        List<DutyScheduleGroupRecord> dutyScheduleGroupRecords;
        DutyScheduleSetCustom lastDutySetCustom = dutyScheduleSetCustomRepository.getOne(new LambdaQueryWrapper<DutyScheduleSetCustom>()
                .eq(DutyScheduleSetCustom::getCustomId, dudyScheduleInitVO.getCustomId())
                .orderByDesc(DutyScheduleSetCustom::getCreateTime), false);
        if (lastDutySetCustom == null) {
            dutyScheduleGroupRecords = new ArrayList<>();
        } else {
            dutyScheduleGroupRecords = dutyScheduleGroupRecordRepository.list(new LambdaQueryWrapper<DutyScheduleGroupRecord>()
                    .eq(DutyScheduleGroupRecord::getCustomId, dudyScheduleInitVO.getCustomId())
                    .eq(DutyScheduleGroupRecord::getSetCustomId, lastDutySetCustom.getId()));
            if (CollectionUtils.isEmpty(dutyScheduleGroupRecords)) {
                dutyScheduleGroupRecords = new ArrayList<>();
            }
        }
        List<String> setypes = SeTypeEnum.getAllAdminCode();
        List<String> dutyTypes = SetDutyTypeEnum.getAllCode();
        List<DutyPersonInitDetailVO> dutyPersonInitDetailVOS = new ArrayList<>();
        for (String setype : setypes) {
            List<DutyPersonInitVO> dutyPersonInitVOS = new ArrayList<>();
            for (String dutyType : dutyTypes) {
                List<ParamGroupDuty> baseGroupInfos = paramGroupDutyRepository.list(new LambdaQueryWrapper<ParamGroupDuty>()
                        .eq(ParamGroupDuty::getCustomId, dudyScheduleInitVO.getCustomId())
                        .eq(ParamGroupDuty::getSeType, setype)
                        .eq(ParamGroupDuty::getSType, dutyType));
                if (CollectionUtils.isEmpty(baseGroupInfos)) {
                    DutyPersonInitVO dutyPersonInitVO = new DutyPersonInitVO();
                    dutyPersonInitVO.setDutyType(dutyType);
                    dutyPersonInitVO.setSeType(setype);
                    dutyPersonInitVO.setTypeName(SetDutyTypeEnum.getDescByCode(dutyType));
                    dutyPersonInitVOS.add(dutyPersonInitVO);
                    continue;
                }
                List<BasePersonInfo> persons = getPersonInCustomGroup(dudyScheduleInitVO.getCustomId(), setype, dutyType);
                persons.forEach(i -> i.setGlobalSort(i.getGlobalSort().replaceAll("[^0-9]", "")));
                if (CollectionUtils.isEmpty(persons)) {
                    throw new Exception("无法获取人员，请确认H4A配置中，以下值班群组是否为空群组或包括非本关区人员：" + SetDutyTypeEnum.getDescByCode(dutyType)+ SeTypeEnum.getDescByCode(setype)
                           );
                }
                List<DutyScheduleGroupRecord> thisTypeRecord = dutyScheduleGroupRecords.stream().filter(i -> (setype.equals(i.getSeType()) &&
                        dutyType.equals(i.getDutyType())))
                        .collect(Collectors.toList());
                String startNum = "0";
                if (!CollectionUtils.isEmpty(thisTypeRecord)) {
                    startNum = thisTypeRecord.get(0).getFinalPersonSort();
                }
                if (startNum == null) {
                    startNum = "0";
                }

                BasePersonInfo lastPerson = new BasePersonInfo();
                List<BasePersonInfo> basePersonInfos = dutySortUtil.sortPerson(persons, baseGroupInfos);
                if (startNum.equals("0")) {
                    lastPerson = persons.stream().min(PersonCompareUtil.comparePersonForSort()).orElse(null);
                } else {
                    BasePersonInfo startPerson = new BasePersonInfo();
                    startPerson.setGlobalSort(startNum);


                    if (!CollectionUtils.isEmpty(thisTypeRecord)) {
                    for(int i = 0;i < basePersonInfos.size();i++){
                       BasePersonInfo basePersonInfo = basePersonInfos.get(i);
                        DutyScheduleGroupRecord dutyScheduleGroupRecord = thisTypeRecord.get(0);
                      if (basePersonInfo.getUserno().equals(dutyScheduleGroupRecord.getFinalPersonNo())){
                           if (i == basePersonInfos.size() -1){
                               lastPerson = basePersonInfos.get(0);
                           }else {
                               lastPerson = basePersonInfos.get(i+1);
                            }
                        }
                    }
                }else {
                        lastPerson = null;
                    }
                }
                    if (lastPerson == null) {
                    lastPerson = basePersonInfos.get(0);
                }
                DutyPersonInitVO dutyPersonInitVO = new DutyPersonInitVO();
                dutyPersonInitVO.setDutyType(dutyType);
                dutyPersonInitVO.setSeType(setype);
                dutyPersonInitVO.setTypeName(SetDutyTypeEnum.getDescByCode(dutyType));
                dutyPersonInitVO.setPersonName(lastPerson.getUsername());
                dutyPersonInitVO.setPersonNo(lastPerson.getUserno());
                dutyPersonInitVO.setGlobalSort(lastPerson.getGlobalSort());
                dutyPersonInitVOS.add(dutyPersonInitVO);
            }
            DutyPersonInitDetailVO dutyPersonInitDetailVO = new DutyPersonInitDetailVO();
//            dutyPersonInitDetailVO.setDutyPersonInitVOS(dutyPersonInitDetailVO.getDutyPersonInitVOS());
            dutyPersonInitDetailVO.setSeType(setype);
            dutyPersonInitDetailVO.setDutyPersonInitVOS(dutyPersonInitVOS);
            dutyPersonInitDetailVOS.add(dutyPersonInitDetailVO);
        }
        return dutyPersonInitDetailVOS;
    }

    @Override
    public Object customsListZG() {
        return baseDeptInfoRepository.list(new LambdaQueryWrapper<BaseDeptInfo>()
                .eq(BaseDeptInfo::getId, systemConfig.getZsCustomId()));
    }

    @Override
    public DudyScheduleListVO dutyScheduleInit(DudyScheduleInitVO dudyScheduleInitVO) throws Exception {
        if (CollectionUtils.isEmpty(dudyScheduleInitVO.getSMonths())) {
            throw new Exception("初始化年份必传!");
        }
        if (StringUtils.isEmpty(dudyScheduleInitVO.getCustomId())) {
            throw new Exception("初始化关区编码必传!");
        }

        List<ParamScheduleSetting> paramScheduleSettingListTYPE_RC = paramScheduleSettingRepository.list(new LambdaQueryWrapper<ParamScheduleSetting>()
                .eq(ParamScheduleSetting::getCustomId, dudyScheduleInitVO.getCustomId())
                .eq(ParamScheduleSetting::getDutyType, SetDutyTypeEnum.TYPE_RC.getValue()));
        List<ParamScheduleSetting> paramScheduleSettingListTYPE_ZMB = paramScheduleSettingRepository.list(new LambdaQueryWrapper<ParamScheduleSetting>()
                .eq(ParamScheduleSetting::getCustomId, dudyScheduleInitVO.getCustomId())
                .eq(ParamScheduleSetting::getDutyType, SetDutyTypeEnum.TYPE_ZMB.getValue()));
        List<ParamScheduleSetting> paramScheduleSettingListTYPE_ZYB = paramScheduleSettingRepository.list(new LambdaQueryWrapper<ParamScheduleSetting>()
                .eq(ParamScheduleSetting::getCustomId, dudyScheduleInitVO.getCustomId())
                .eq(ParamScheduleSetting::getDutyType, SetDutyTypeEnum.TYPE_ZYB.getValue()));
        List<ParamScheduleSetting> paramScheduleSettingListTYPE_ZM = paramScheduleSettingRepository.list(new LambdaQueryWrapper<ParamScheduleSetting>()
                .eq(ParamScheduleSetting::getCustomId, dudyScheduleInitVO.getCustomId())
                .eq(ParamScheduleSetting::getDutyType, SetDutyTypeEnum.TYPE_ZM.getValue()));
        if (CollectionUtils.isEmpty(paramScheduleSettingListTYPE_RC)) {
            throw new HdcException("工作日班未进行排班配置!");
        }
        if (CollectionUtils.isEmpty(paramScheduleSettingListTYPE_ZMB)) {
            throw new HdcException("节假日班未进行排班配置!");
        }
        if (CollectionUtils.isEmpty(paramScheduleSettingListTYPE_ZYB)) {
            throw new HdcException("重要班未进行排班配置!");
        }
        if (CollectionUtils.isEmpty(paramScheduleSettingListTYPE_ZM)) {
            throw new HdcException("周末班未进行排班配置!");
        }
        log.info("start" + LocalDateTime.now());
        String[] tempArray = dudyScheduleInitVO.getSMonths().get(0).split("-");
        Long startYear = Long.valueOf(tempArray[0]);
        Long startMonth = Long.valueOf(tempArray[1]);
        tempArray = dudyScheduleInitVO.getSMonths().get(1).split("-");
        Long endYear = Long.valueOf(tempArray[0]);
        Long endMonth = Long.valueOf(tempArray[1]);
        //todo
        //判断该时间是否已初始化过
        if (dutyScheduleSetCustomRepository.count(new LambdaQueryWrapper<DutyScheduleSetCustom>()
                .ge(DutyScheduleSetCustom::getSYearStart, startYear)
                .le(DutyScheduleSetCustom::getSYearEnd, startMonth)
                .ge(DutyScheduleSetCustom::getSMonthStart, endYear)
                .le(DutyScheduleSetCustom::getSMonthEnd, endMonth)) > 0) {
            throw new Exception("此关区的此时间有初始化记录不能再次初始化！");
        }
        DudyScheduleListVO dudyScheduleListVO = new DudyScheduleListVO();
        DudyScheduleListVO.DailyDudy dailyDudy = new DudyScheduleListVO.DailyDudy();
        DudyScheduleListVO.WeekendDudy weekendDudy = new DudyScheduleListVO.WeekendDudy();
        DudyScheduleListVO.HolidayAndVacationsDudy holidayAndVacationsDudy = new DudyScheduleListVO.HolidayAndVacationsDudy();
        DudyScheduleListVO.ImportantDayDudy importantDayDudy = new DudyScheduleListVO.ImportantDayDudy();
        //获取该关区id下所有的部门.
        List<BaseDeptInfo> baseDeptInfos = baseDeptInfoRepository.list(new LambdaQueryWrapper<BaseDeptInfo>()
                .eq(BaseDeptInfo::getParentid, dudyScheduleInitVO.getCustomId())
//                .eq(BaseDeptInfo::getNotUseKJDept,"0")
                .orderByAsc(BaseDeptInfo::getGlobalSort));
        List<BaseDeptInfo> allDepts = baseDeptInfoRepository.list(new LambdaQueryWrapper<BaseDeptInfo>()
                        .eq(BaseDeptInfo::getCustomId, dudyScheduleInitVO.getCustomId())
//                .eq(BaseDeptInfo::getNotUseKJDept,"0")
        );
        log.info("datas" + LocalDateTime.now());
        //工作日班下的部门列表和部门下的人员列表
        List<String> setypes = SeTypeEnum.getAllSubCode();
        List<String> dutyTypes = SetDutyTypeEnum.getAllCode();
        List<DutyPersonInitDetailVO> dutyPersonInitDetailVOS = new ArrayList<>();

        //获取本关区的历史记录
//        DutyScheduleSetCustomRecordDTO dutyScheduleSetCustomRecord = getLastHaveValueRecord(baseDeptInfos, dudyScheduleInitVO.getCustomId(), dailyDudyTemplates, holidayTemplates, importPersonTemplates);
        log.info("records" + LocalDateTime.now());
        //计算本轮周期的所需人次
        if (endMonth < 12) {
            endMonth = endMonth + 1;
        } else {
            endMonth = 1l;
            endYear = endYear + 1;
        }
        List<ParamHolidays> holidays = paramHolidaysRepository.list(new LambdaQueryWrapper<ParamHolidays>()
                .ge(ParamHolidays::getHolidayDate, LocalDate.of((int) (long) startYear, (int) (long) startMonth, 1))
                .lt(ParamHolidays::getHolidayDate, LocalDate.of((int) (long) endYear, (int) (long) endMonth, 1))
                .eq(ParamHolidays::getHolidayType, HolidaysEnum.HOLIDAY.getValue())
                .eq(ParamHolidays::getCustomId, dudyScheduleInitVO.getCustomId()));
        List<ParamHolidays> importantDays = paramHolidaysRepository.list(new LambdaQueryWrapper<ParamHolidays>()
                .ge(ParamHolidays::getHolidayDate, LocalDate.of((int) (long) startYear, (int) (long) startMonth, 1))
                .lt(ParamHolidays::getHolidayDate, LocalDate.of((int) (long) endYear, (int) (long) endMonth, 1))
                .eq(ParamHolidays::getHolidayType, HolidaysEnum.IMPORTANT_PERIOD.getValue())
                .eq(ParamHolidays::getCustomId, dudyScheduleInitVO.getCustomId()));
        List<ParamHolidays> hoildayExchanges = paramHolidaysRepository.list(new LambdaQueryWrapper<ParamHolidays>()
                .ge(ParamHolidays::getHolidayDate, LocalDate.of((int) (long) startYear, (int) (long) startMonth, 1))
                .lt(ParamHolidays::getHolidayDate, LocalDate.of((int) (long) endYear, (int) (long) endMonth, 1))
                .eq(ParamHolidays::getHolidayType, HolidaysEnum.HOLIDAY_EXCHANGE.getValue())
                .eq(ParamHolidays::getCustomId, dudyScheduleInitVO.getCustomId()));
        //24.08.02
        List<ParamScheduleSetting> rcSetting = paramScheduleSettingRepository.list(new LambdaQueryWrapper<ParamScheduleSetting>()
                .eq(ParamScheduleSetting::getCustomId, dudyScheduleInitVO.getCustomId())
                .eq(ParamScheduleSetting::getDutyType, SetDutyTypeEnum.TYPE_RC.getValue()));
        List<ParamScheduleSetting> zmbSetting = paramScheduleSettingRepository.list(new LambdaQueryWrapper<ParamScheduleSetting>()
                .eq(ParamScheduleSetting::getCustomId, dudyScheduleInitVO.getCustomId())
                .eq(ParamScheduleSetting::getDutyType, SetDutyTypeEnum.TYPE_ZMB.getValue()));
        List<ParamScheduleSetting> zybSetting = paramScheduleSettingRepository.list(new LambdaQueryWrapper<ParamScheduleSetting>()
                .eq(ParamScheduleSetting::getCustomId, dudyScheduleInitVO.getCustomId())
                .eq(ParamScheduleSetting::getDutyType, SetDutyTypeEnum.TYPE_ZYB.getValue()));
        List<ParamScheduleSetting> zmSetting = paramScheduleSettingRepository.list(new LambdaQueryWrapper<ParamScheduleSetting>()
                .eq(ParamScheduleSetting::getCustomId, dudyScheduleInitVO.getCustomId())
                .eq(ParamScheduleSetting::getDutyType, SetDutyTypeEnum.TYPE_ZM.getValue()));
        Integer hoilDayCount = holidays.size() * zmbSetting.size();
        Integer importantCount = importantDays.size() * zybSetting.size();
        Integer commonCount = DateUtil.getCommonCount(startYear, startMonth, endYear, endMonth, holidays, importantDays, hoildayExchanges, rcSetting, zmSetting);
        Integer weekendCount = DateUtil.getWeekendCount(startYear, startMonth, endYear, endMonth, holidays, importantDays, hoildayExchanges, rcSetting, zmSetting);
        List<ParamGroupDuty> paramGroupDuties = paramGroupDutyRepository.list(new LambdaQueryWrapper<ParamGroupDuty>()
                .eq(ParamGroupDuty::getCustomId, dudyScheduleInitVO.getCustomId()));
        //工作日班
        List<BaseDeptInfo> hasGroupInfos = groupCheckInfo(dudyScheduleInitVO, paramGroupDuties, baseDeptInfos, allDepts);
        List<DudyScheduleListVO.DudyTemplate> dutyTemplate = createSTemplates(paramGroupDuties, dudyScheduleInitVO, hasGroupInfos, allDepts, commonCount, "3", "1");
        List<DudyScheduleListVO.DudyTemplate> DedutyTemplate = createDTemplates(paramGroupDuties, dudyScheduleInitVO, hasGroupInfos, allDepts, commonCount, "2", "1");
        dutyTemplate = mergeTemplate(dutyTemplate, DedutyTemplate, baseDeptInfos);
        dailyDudy.setDudyTemplate(dutyTemplate);
        dudyScheduleListVO.setDailyDudy(dailyDudy);
        List<DudyScheduleListVO.DudyTemplate> hoildayTempateS = createSTemplates(paramGroupDuties, dudyScheduleInitVO, hasGroupInfos, allDepts, hoilDayCount, "3", "2");
        List<DudyScheduleListVO.DudyTemplate> hoildayTempateD = createDTemplates(paramGroupDuties, dudyScheduleInitVO, hasGroupInfos, allDepts, hoilDayCount, "2", "2");
        hoildayTempateS = mergeTemplate(hoildayTempateS, hoildayTempateD, baseDeptInfos);
        holidayAndVacationsDudy.setDudyTemplate(hoildayTempateS);
        dudyScheduleListVO.setHolidayAndVacationsDudy(holidayAndVacationsDudy);
        List<DudyScheduleListVO.DudyTemplate> importTempateS = createSTemplates(paramGroupDuties, dudyScheduleInitVO, hasGroupInfos, allDepts, importantCount, "3", "3");
        List<DudyScheduleListVO.DudyTemplate> importTempateD = createDTemplates(paramGroupDuties, dudyScheduleInitVO, hasGroupInfos, allDepts, importantCount, "2", "3");
        importTempateS = mergeTemplate(importTempateS, importTempateD, baseDeptInfos);
        importantDayDudy.setDudyTemplate(importTempateS);
        dudyScheduleListVO.setImportantDayDudy(importantDayDudy);
        List<DudyScheduleListVO.DudyTemplate> weekendS = createSTemplates(paramGroupDuties, dudyScheduleInitVO, hasGroupInfos, allDepts, weekendCount, "3", "4");
        List<DudyScheduleListVO.DudyTemplate> weekendD = createDTemplates(paramGroupDuties, dudyScheduleInitVO, hasGroupInfos, allDepts, weekendCount, "2", "4");
        weekendS = mergeTemplate(weekendS, weekendD, baseDeptInfos);
        weekendDudy.setDudyTemplate(weekendS);
        ;
        dudyScheduleListVO.setWeekendDudy(weekendDudy);
        log.info("results" + LocalDateTime.now());
        return dudyScheduleListVO;
    }

    private List<DutyScheduleInfo> getParents(List<DutyScheduleInfo> dutyScheduleInfos, String customNames) {
        List<BaseDeptInfo> deptInfoList = guavacacheUtils.getDepts();
        Map<String, BaseDeptInfo> deptInfoMap = deptInfoList.stream().collect(Collectors.toMap(BaseDeptInfo::getId, i -> i));
        List<String> customNameList = Arrays.asList(customNames.split(","));
        for (DutyScheduleInfo dutyScheduleInfo : dutyScheduleInfos) {
            BaseDeptInfo baseDeptInfo = deptInfoMap.get(dutyScheduleInfo.getDDept());
            if (baseDeptInfo != null) {
                BaseDeptInfo parent = deptInfoMap.get(baseDeptInfo.getParentid());
                if (parent != null && !systemConfig.getZsCustomName().equals(parent.getDeptName()) && !customNameList.contains(parent.getDeptName())) {
                    dutyScheduleInfo.setDDeptname(dutyScheduleInfo.getDDeptname() + "(" + parent.getDeptName() + ")");
                    dutyScheduleInfo.setDDept(parent.getId());
                }
            }
            if ("科员".equals(dutyScheduleInfo.getDUserjob()) || "科领导".equals(dutyScheduleInfo.getDUserjob())) {
                dutyScheduleInfo.setDType("1");
            } else if ("处领导".equals(dutyScheduleInfo.getDUserjob()) || "关领导".equals(dutyScheduleInfo.getDUserjob())) {
                dutyScheduleInfo.setDType("2");
            }
        }
        return dutyScheduleInfos;
    }

    private DudyLineTemplateDTO getHoilDayDLevlCount(List<BaseDeptInfo> baseDeptInfos, List<DudyScheduleListVO.DudyTemplate> dailyDudyTemplates, Integer commonCount, DutyScheduleSetCustomRecord dutyScheduleSetCustomRecords, BaseDeptInfo custom, DutyScheduleTypeEnum typeImportantDlevel) {
        List<DudyScheduleListVO.DudyTemplate> returnList = new ArrayList<>();
        List<DudyScheduleListVO.DudyTemplate> lineList = new ArrayList<>();
        List<DudyScheduleListVO.DudyTemplate> currentTemplates = new ArrayList<>();
        Map<String, DudyScheduleListVO.DudyTemplate> returnMap = new HashMap<>();
        List<DutyScheduleSetCustomRecord> currentRecord = new ArrayList<>();
        Integer round = 1;
        Map<String, String> baseDeptMap = baseDeptInfos.stream().collect(Collectors.toMap(i -> i.getId(), i -> i.getGlobalSort()));
        Long manOrder = 0l;
        if (dutyScheduleSetCustomRecords != null) {
            manOrder = Long.valueOf(baseDeptMap.get(dutyScheduleSetCustomRecords.getDeptId()));
            Integer finalRound = round;
            currentRecord = Arrays.asList(dutyScheduleSetCustomRecords);
            dailyDudyTemplates.forEach(i -> i.setRound(finalRound));

            currentTemplates.forEach(i -> i.setRound(finalRound - 1));
            Map<String, DudyScheduleListVO.DudyTemplate> dudyTemplateMap = dailyDudyTemplates
                    .stream().collect(Collectors.toMap(i -> i.getDudyDeptId(), i -> i));
            for (String dept : dudyTemplateMap.keySet()) {
                String sort = baseDeptMap.get(dept);
                Long order = 0l;
                if (StringUtils.isEmpty(sort)) {
                    continue;
                } else {
                    order = Long.valueOf(sort);
                }
                if (order > manOrder) {
//                          manOrder=order;
                    currentTemplates.add(dudyTemplateMap.get(dept));

                }
            }
            currentTemplates = currentTemplates.stream().sorted(Comparator.comparing(i -> i.getSort()))
                    .collect(Collectors.toList());
        }
        int flag = 0;
        if (!CollectionUtils.isEmpty(currentRecord) && Arrays.asList(DutyScheduleSetCustomRecordStatusEnum.NOT_PASSED_YET.getValue()
                , DutyScheduleSetCustomRecordStatusEnum.NOT_USE.getValue()).contains(dutyScheduleSetCustomRecords.getStatus())) {
            for (int a = 0; a < currentRecord.size(); a++) {
                DutyScheduleSetCustomRecord tempCurrentRecord = currentRecord.get(a);
                DudyScheduleListVO.DudyTemplate dudyTemplate = new DudyScheduleListVO.DudyTemplate();
                BeanUtils.copyProperties(dailyDudyTemplates.stream().filter(i -> i.getDudyDeptId().equals(tempCurrentRecord.getDeptId()))
                        .collect(Collectors.toList()).get(0), dudyTemplate);
                Integer addValue = 0;
                if (dudyTemplate.getDivisionLevelDudyNumber() < currentRecord.get(a).getNeedCount()) {
                    addValue = dudyTemplate.getDivisionLevelDudyNumber();
                    flag += addValue;
                    DutyScheduleSetCustomRecord finalCurrentRecord = currentRecord.get(a);
                    currentTemplates = currentTemplates.stream().filter(i -> !i.getDudyDeptId().equals(finalCurrentRecord.getDeptId()))
                            .collect(Collectors.toList());
                    dudyTemplate.setDivisionLevelDudyNumber(dudyTemplate.getDivisionLevelDudyNumber());
                    dudyTemplate.setRound(round);
                } else {
                    addValue = (int) (long) currentRecord.get(a).getNeedCount();
                    flag += addValue;
                    DutyScheduleSetCustomRecord finalCurrentRecord = currentRecord.get(a);
                    currentTemplates = currentTemplates.stream().filter(i -> !i.getDudyDeptId().equals(finalCurrentRecord.getDeptId()))
                            .collect(Collectors.toList());
                    dudyTemplate.setDivisionLevelDudyNumber((int) (long) currentRecord.get(a).getNeedCount());
                    dudyTemplate.setRound(round);
                }
                if (flag >= commonCount) {
                    dudyTemplate.setRound(round - 1);
                    dudyTemplate.setDivisionLevelDudyNumber(addValue - (flag - commonCount));
                    returnList.add(dudyTemplate);
                    lineList.add(dudyTemplate);
                    for (String key : returnMap.keySet()) {
                        returnList.add(returnMap.get(key));
                        lineList.add(returnMap.get(key));
                    }
                    ListIterator<DudyScheduleListVO.DudyTemplate> listIterator = dailyDudyTemplates.listIterator();
                    listIterator = dailyDudyTemplates.listIterator();
                    while (listIterator.hasNext()) {
                        DudyScheduleListVO.DudyTemplate temp = new DudyScheduleListVO.DudyTemplate();
                        BeanUtils.copyProperties(listIterator.next(), temp);
                        if (!returnList.stream().map(i -> i.getDudyDeptId()).collect(Collectors.toList()).contains(temp.getDudyDeptId())) {
                            temp.setDivisionLevelDudyNumber(0);
                            returnList.add(temp);
                            lineList.add(temp);
                        }
                    }
                    DudyLineTemplateDTO dudyLineTemplateDTO = new DudyLineTemplateDTO();
                    dudyLineTemplateDTO.setLineList(returnList);
                    dudyLineTemplateDTO.setSaveList(returnList);
                    return dudyLineTemplateDTO;
                } else {
                    dudyTemplate.setRound(round);
                    returnMap.put(dudyTemplate.getDudyDeptId(), dudyTemplate);
                    lineList.add(dudyTemplate);
                }
            }
        }
        if (commonCount == 0) {
            ListIterator<DudyScheduleListVO.DudyTemplate> listIterator = dailyDudyTemplates.listIterator();
            listIterator = dailyDudyTemplates.listIterator();
            while (listIterator.hasNext()) {
                DudyScheduleListVO.DudyTemplate dudyTemplate = new DudyScheduleListVO.DudyTemplate();
                BeanUtils.copyProperties(listIterator.next(), dudyTemplate);
                dudyTemplate.setDivisionLevelDudyNumber(0);
                dudyTemplate.setRound(round);
                returnList.add(dudyTemplate);
                lineList.add(dudyTemplate);
            }
            DudyLineTemplateDTO dudyLineTemplateDTO = new DudyLineTemplateDTO();
            dudyLineTemplateDTO.setLineList(returnList);
            dudyLineTemplateDTO.setSaveList(returnList);
            return dudyLineTemplateDTO;
        }
        if (dailyDudyTemplates.stream().map(DudyScheduleListVO.DudyTemplate::getDivisionLevelDudyNumber).reduce((a, b) -> a + b).orElse(0) == 0) {
            ListIterator<DudyScheduleListVO.DudyTemplate> listIterator = dailyDudyTemplates.listIterator();
            listIterator = dailyDudyTemplates.listIterator();
            while (listIterator.hasNext()) {
                DudyScheduleListVO.DudyTemplate dudyTemplate = new DudyScheduleListVO.DudyTemplate();
                BeanUtils.copyProperties(listIterator.next(), dudyTemplate);
                dudyTemplate.setDivisionLevelDudyNumber(0);
                dudyTemplate.setRound(round);
                returnList.add(dudyTemplate);
                lineList.add(dudyTemplate);
            }
            DudyLineTemplateDTO dudyLineTemplateDTO = new DudyLineTemplateDTO();
            dudyLineTemplateDTO.setLineList(returnList);
            dudyLineTemplateDTO.setSaveList(returnList);
            return dudyLineTemplateDTO;
        }
        while (flag < commonCount) {
            ListIterator<DudyScheduleListVO.DudyTemplate> listIterator = null;
            if (!org.apache.commons.collections4.CollectionUtils.isEmpty(currentTemplates) && currentTemplates.size() != dailyDudyTemplates.size()) {
                listIterator = currentTemplates.listIterator();
            } else {
                listIterator = dailyDudyTemplates.listIterator();
            }
            while (listIterator.hasNext()) {
                DudyScheduleListVO.DudyTemplate dudyTemplate = new DudyScheduleListVO.DudyTemplate();
                BeanUtils.copyProperties(listIterator.next(), dudyTemplate);
                dudyTemplate.setRound(round);
                if (flag == commonCount) {
                    if (returnMap.get(dudyTemplate.getDudyDeptId()) == null) {
                        dudyTemplate.setDivisionLevelDudyNumber(0);
                        if (round > 1) {
                            dudyTemplate.setRound(round - 1);
                        }
                        returnList.add(dudyTemplate);
                        lineList.add(dudyTemplate);
                        returnMap.put(dudyTemplate.getDudyDeptId(), dudyTemplate);
                    }
                    continue;
                }
                flag += dudyTemplate.getDivisionLevelDudyNumber();
                if (flag >= commonCount) {
                    int current = dudyTemplate.getDivisionLevelDudyNumber() - (flag - commonCount);
                    flag = commonCount;
                    if (returnMap.get(dudyTemplate.getDudyDeptId()) == null) {
                        dudyTemplate.setDivisionLevelDudyNumber(current);
                        returnList.add(dudyTemplate);
                        lineList.add(dudyTemplate);
                        returnMap.put(dudyTemplate.getDudyDeptId(), dudyTemplate);
                    } else {
                        DudyScheduleListVO.DudyTemplate temp = returnMap.get(dudyTemplate.getDudyDeptId());
                        DudyScheduleListVO.DudyTemplate line = new DudyScheduleListVO.DudyTemplate();
                        BeanUtils.copyProperties(dudyTemplate, line);
                        line.setDivisionLevelDudyNumber(current);
                        lineList.add(line);
                        dudyTemplate.setDivisionLevelDudyNumber(temp.getDivisionLevelDudyNumber() + current);
                        returnMap.put(dudyTemplate.getDudyDeptId(), dudyTemplate);
                    }
                } else if (flag < commonCount) {
                    if (returnMap.get(dudyTemplate.getDudyDeptId()) == null) {
                        returnList.add(dudyTemplate);
                        DudyScheduleListVO.DudyTemplate line = new DudyScheduleListVO.DudyTemplate();
                        BeanUtils.copyProperties(dudyTemplate, line);
                        lineList.add(line);
                        returnMap.put(dudyTemplate.getDudyDeptId(), dudyTemplate);
                    } else {
                        DudyScheduleListVO.DudyTemplate temp = returnMap.get(dudyTemplate.getDudyDeptId());
                        DudyScheduleListVO.DudyTemplate line = new DudyScheduleListVO.DudyTemplate();
                        BeanUtils.copyProperties(dudyTemplate, line);
                        lineList.add(line);
                        dudyTemplate.setDivisionLevelDudyNumber(temp.getDivisionLevelDudyNumber() + dudyTemplate.getDivisionLevelDudyNumber());
                        returnMap.put(dudyTemplate.getDudyDeptId(), dudyTemplate);
                    }
                }
            }
            round++;
            currentTemplates = dailyDudyTemplates;
        }
        returnList = new ArrayList<>();
        for (String key : returnMap.keySet()) {
            returnList.add(returnMap.get(key));
        }
        if (!CollectionUtils.isEmpty(returnList)) {
            for (DudyScheduleListVO.DudyTemplate dudyTemplate : dailyDudyTemplates) {
                if (!returnList.stream().map(DudyScheduleListVO.DudyTemplate::getDudyDeptId).collect(Collectors.toList())
                        .contains(dudyTemplate.getDudyDeptId())) {
                    DudyScheduleListVO.DudyTemplate temp = new DudyScheduleListVO.DudyTemplate();
                    BeanUtils.copyProperties(dudyTemplate, temp);
                    temp.setDivisionLevelDudyNumber(0);
                    returnList.add(temp);
                }
            }
            returnList = returnList.stream().sorted(Comparator.comparing(i -> i.getSort())).collect(Collectors.toList());
        }
        DudyLineTemplateDTO dudyLineTemplateDTO = new DudyLineTemplateDTO();
//        lineList=lineList.stream().sorted(Comparator.comparing(i->i.getSort())).collect(Collectors.toList());
        dudyLineTemplateDTO.setLineList(lineList);
        dudyLineTemplateDTO.setSaveList(returnList);
        Integer maxRound = returnList.stream().map(DudyScheduleListVO.DudyTemplate::getRound).max(Comparator.comparingInt(i -> i)).orElse(1);
        Long finalManOrder = manOrder;
        returnList.forEach(i -> {
            if (Long.parseLong(i.getSort() != null ? i.getSort() : "0") < finalManOrder && i.getSectionLevelDudyNumber() == 0) {
                i.setRound(maxRound);
            }
        });
        return dudyLineTemplateDTO;
    }

    private List<DudyScheduleListVO.DudyTemplate> getImportantDayDLevlCount(List<DudyScheduleListVO.DudyTemplate> dailyDudyTemplates, Integer commonCount, List<DutyScheduleSetCustomRecord> dutyScheduleSetCustomRecords, BaseDeptInfo custom) {
        List<DudyScheduleListVO.DudyTemplate> returnList = new ArrayList<>();
        List<DudyScheduleListVO.DudyTemplate> currentTemplates = dailyDudyTemplates;
        Map<String, DudyScheduleListVO.DudyTemplate> returnMap = new HashMap<>();
        DutyScheduleSetCustomRecord currentRecord = null;
        if (!CollectionUtils.isEmpty(dutyScheduleSetCustomRecords)) {
            dutyScheduleSetCustomRecords = dutyScheduleSetCustomRecords.stream().filter(i -> DutyScheduleTypeEnum
                    .TYPE_IMPORTANT_DLEVEL.getValue().equals(i.getSType())).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(dutyScheduleSetCustomRecords)) {
                List<DutyScheduleSetCustomRecord> temp = dutyScheduleSetCustomRecords;
                if (!CollectionUtils.isEmpty(dutyScheduleSetCustomRecords)) {
                    currentTemplates = dailyDudyTemplates.stream().filter(j -> temp.stream().map(i -> i.getDeptId())
                            .collect(Collectors.toList()).contains(j.getDudyDeptId())).collect(Collectors.toList());
                }
                dutyScheduleSetCustomRecords = dutyScheduleSetCustomRecords.stream().filter(i ->
                        DutyScheduleSetCustomRecordStatusEnum.NOT_PASSED_YET.getValue().equals(i.getNeedCount())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(dutyScheduleSetCustomRecords)) {
                    currentRecord = dutyScheduleSetCustomRecords.get(0);
                }
            }
        }
        ListIterator<DudyScheduleListVO.DudyTemplate> listIterator = dailyDudyTemplates.listIterator();
        int flag = 0;
        if (currentRecord != null) {
            DutyScheduleSetCustomRecord tempCurrentRecord = currentRecord;
            DudyScheduleListVO.DudyTemplate dudyTemplate = new DudyScheduleListVO.DudyTemplate();
            BeanUtils.copyProperties(currentTemplates.stream().filter(i -> i.getDudyDeptId().equals(tempCurrentRecord.getDeptId()))
                    .collect(Collectors.toList()).get(0), dudyTemplate);
            if (dudyTemplate.getDivisionLevelDudyNumber() < currentRecord.getNeedCount()) {
                flag += dudyTemplate.getDivisionLevelDudyNumber();
                currentTemplates.remove(dudyTemplate);
                dudyTemplate.setDivisionLevelDudyNumber(flag);
                returnList.add(dudyTemplate);
                returnMap.put(dudyTemplate.getDudyDeptId(), dudyTemplate);
            } else {
                flag += currentRecord.getNeedCount();
                currentTemplates.remove(dudyTemplate);
                dudyTemplate.setDivisionLevelDudyNumber(flag);
                returnList.add(dudyTemplate);
                returnMap.put(dudyTemplate.getDudyDeptId(), dudyTemplate);
            }
            if (flag > commonCount) {
                flag = commonCount;
                dudyTemplate.setDivisionLevelDudyNumber(flag);
                returnList.add(dudyTemplate);
                return returnList;
            }
        }
        if (commonCount == 0) {
            while (listIterator.hasNext()) {
                DudyScheduleListVO.DudyTemplate dudyTemplate = new DudyScheduleListVO.DudyTemplate();
                BeanUtils.copyProperties(listIterator.next(), dudyTemplate);
                dudyTemplate.setDivisionLevelDudyNumber(0);
                returnList.add(dudyTemplate);
            }
            return returnList;
        }
        if (dailyDudyTemplates.stream().map(DudyScheduleListVO.DudyTemplate::getDivisionLevelDudyNumber).reduce((a, b) -> a + b).orElse(0) == 0) {
            while (listIterator.hasNext()) {
                DudyScheduleListVO.DudyTemplate dudyTemplate = new DudyScheduleListVO.DudyTemplate();
                BeanUtils.copyProperties(listIterator.next(), dudyTemplate);
                dudyTemplate.setDivisionLevelDudyNumber(0);
                returnList.add(dudyTemplate);
            }
            return returnList;
        }
        while (flag < commonCount) {
            while (listIterator.hasNext()) {
                DudyScheduleListVO.DudyTemplate dudyTemplate = new DudyScheduleListVO.DudyTemplate();
                BeanUtils.copyProperties(listIterator.next(), dudyTemplate);
                if (flag == commonCount) {
                    if (returnMap.get(dudyTemplate.getDudyDeptId()) == null) {
                        dudyTemplate.setDivisionLevelDudyNumber(0);
                        returnList.add(dudyTemplate);
                        returnMap.put(dudyTemplate.getDudyDeptId(), dudyTemplate);
                    }
                    continue;
                }
                flag += dudyTemplate.getDivisionLevelDudyNumber();
                if (flag >= commonCount) {
                    int current = dudyTemplate.getDivisionLevelDudyNumber() - (flag - commonCount);
                    flag = commonCount;
                    if (returnMap.get(dudyTemplate.getDudyDeptId()) == null) {
                        dudyTemplate.setDivisionLevelDudyNumber(current);
                        returnList.add(dudyTemplate);
                        returnMap.put(dudyTemplate.getDudyDeptId(), dudyTemplate);
                    } else {
                        DudyScheduleListVO.DudyTemplate temp = returnMap.get(dudyTemplate.getDudyDeptId());
                        dudyTemplate.setDivisionLevelDudyNumber(temp.getDivisionLevelDudyNumber() + current);
                        returnMap.put(dudyTemplate.getDudyDeptId(), dudyTemplate);
                    }
                } else if (flag < commonCount) {
                    if (returnMap.get(dudyTemplate.getDudyDeptId()) == null) {
                        returnList.add(dudyTemplate);
                        returnMap.put(dudyTemplate.getDudyDeptId(), dudyTemplate);
                    } else {
                        DudyScheduleListVO.DudyTemplate temp = returnMap.get(dudyTemplate.getDudyDeptId());
                        dudyTemplate.setDivisionLevelDudyNumber(temp.getDivisionLevelDudyNumber() + dudyTemplate.getDivisionLevelDudyNumber());
                        returnMap.put(dudyTemplate.getDudyDeptId(), dudyTemplate);
                    }
                }
            }
            currentTemplates = dailyDudyTemplates;
            listIterator = currentTemplates.listIterator();
        }
        returnList = new ArrayList<>();
        for (String key : returnMap.keySet()) {
            returnList.add(returnMap.get(key));
        }
        if (!CollectionUtils.isEmpty(returnList)) {
            returnList = returnList.stream().sorted(Comparator.comparing(i -> i.getSort())).collect(Collectors.toList());
        }
        return returnList;
    }

    private List<DudyScheduleListVO.DudyTemplate> getImportantDayCount(List<DudyScheduleListVO.DudyTemplate> dailyDudyTemplates, Integer commonCount, List<DutyScheduleSetCustomRecord> dutyScheduleSetCustomRecords, BaseDeptInfo custom) {
        List<DudyScheduleListVO.DudyTemplate> returnList = new ArrayList<>();
        List<DudyScheduleListVO.DudyTemplate> currentTemplates = dailyDudyTemplates;
        Map<String, DudyScheduleListVO.DudyTemplate> returnMap = new HashMap<>();
        DutyScheduleSetCustomRecord currentRecord = null;
        if (!CollectionUtils.isEmpty(dutyScheduleSetCustomRecords)) {
            dutyScheduleSetCustomRecords = dutyScheduleSetCustomRecords.stream().filter(i -> DutyScheduleTypeEnum
                    .TYPE_IMPORTANT.getValue().equals(i.getSType())).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(dutyScheduleSetCustomRecords)) {
                List<DutyScheduleSetCustomRecord> temp = dutyScheduleSetCustomRecords;
                if (!CollectionUtils.isEmpty(dutyScheduleSetCustomRecords)) {
                    currentTemplates = dailyDudyTemplates.stream().filter(j -> temp.stream().map(i -> i.getDeptId())
                            .collect(Collectors.toList()).contains(j.getDudyDeptId())).collect(Collectors.toList());
                }
                dutyScheduleSetCustomRecords = dutyScheduleSetCustomRecords.stream().filter(i ->
                        DutyScheduleSetCustomRecordStatusEnum.NOT_PASSED_YET.getValue().equals(i.getNeedCount())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(dutyScheduleSetCustomRecords)) {
                    currentRecord = dutyScheduleSetCustomRecords.get(0);
                }
            }
        }
        ListIterator<DudyScheduleListVO.DudyTemplate> listIterator = dailyDudyTemplates.listIterator();
        int flag = 0;
        if (currentRecord != null) {
            DutyScheduleSetCustomRecord tempCurrentRecord = currentRecord;
            DudyScheduleListVO.DudyTemplate dudyTemplate = new DudyScheduleListVO.DudyTemplate();
            BeanUtils.copyProperties(currentTemplates.stream().filter(i -> i.getDudyDeptId().equals(tempCurrentRecord.getDeptId()))
                    .collect(Collectors.toList()).get(0), dudyTemplate);
            if (dudyTemplate.getSectionLevelDudyNumber() < currentRecord.getNeedCount()) {
                flag += dudyTemplate.getSectionLevelDudyNumber();
                currentTemplates.remove(dudyTemplate);
                dudyTemplate.setSectionLevelDudyNumber(flag);
                returnList.add(dudyTemplate);
                returnMap.put(dudyTemplate.getDudyDeptId(), dudyTemplate);
            } else {
                flag += currentRecord.getNeedCount();
                currentTemplates.remove(dudyTemplate);
                dudyTemplate.setSectionLevelDudyNumber(flag);
                returnList.add(dudyTemplate);
                returnMap.put(dudyTemplate.getDudyDeptId(), dudyTemplate);
            }
            if (flag > commonCount) {
                flag = commonCount;
                dudyTemplate.setSectionLevelDudyNumber(flag);
                returnList.add(dudyTemplate);
                return returnList;
            }
        }
        if (commonCount == 0) {
            while (listIterator.hasNext()) {
                DudyScheduleListVO.DudyTemplate dudyTemplate = new DudyScheduleListVO.DudyTemplate();
                BeanUtils.copyProperties(listIterator.next(), dudyTemplate);
                dudyTemplate.setSectionLevelDudyNumber(0);
                returnList.add(dudyTemplate);
            }
            return returnList;
        }
        if (dailyDudyTemplates.stream().map(DudyScheduleListVO.DudyTemplate::getSectionLevelDudyNumber).reduce((a, b) -> a + b).orElse(0) == 0) {
            while (listIterator.hasNext()) {
                DudyScheduleListVO.DudyTemplate dudyTemplate = new DudyScheduleListVO.DudyTemplate();
                BeanUtils.copyProperties(listIterator.next(), dudyTemplate);
                dudyTemplate.setSectionLevelDudyNumber(0);
                returnList.add(dudyTemplate);
            }
            return returnList;
        }
        if (dailyDudyTemplates.stream().map(DudyScheduleListVO.DudyTemplate::getSectionLevelDudyNumber).reduce((a, b) -> a + b).orElse(0) == 0) {
            while (listIterator.hasNext()) {
                DudyScheduleListVO.DudyTemplate dudyTemplate = new DudyScheduleListVO.DudyTemplate();
                BeanUtils.copyProperties(listIterator.next(), dudyTemplate);
                dudyTemplate.setSectionLevelDudyNumber(0);
                returnMap.put(dudyTemplate.getDudyDeptId(), dudyTemplate);
            }
        }
        while (flag < commonCount) {
            while (listIterator.hasNext()) {
                DudyScheduleListVO.DudyTemplate dudyTemplate = new DudyScheduleListVO.DudyTemplate();
                BeanUtils.copyProperties(listIterator.next(), dudyTemplate);
                if (flag == commonCount) {
                    if (returnMap.get(dudyTemplate.getDudyDeptId()) == null) {
                        dudyTemplate.setSectionLevelDudyNumber(0);
                        returnList.add(dudyTemplate);
                        returnMap.put(dudyTemplate.getDudyDeptId(), dudyTemplate);
                    }
                    continue;
                }
                flag += dudyTemplate.getSectionLevelDudyNumber();
                if (flag >= commonCount) {
                    int current = dudyTemplate.getSectionLevelDudyNumber() - (flag - commonCount);
                    flag = commonCount;
                    if (returnMap.get(dudyTemplate.getDudyDeptId()) == null) {
                        dudyTemplate.setSectionLevelDudyNumber(current);
                        returnList.add(dudyTemplate);
                        returnMap.put(dudyTemplate.getDudyDeptId(), dudyTemplate);
                    } else {
                        DudyScheduleListVO.DudyTemplate temp = returnMap.get(dudyTemplate.getDudyDeptId());
                        dudyTemplate.setSectionLevelDudyNumber(temp.getSectionLevelDudyNumber() + current);
                        returnMap.put(dudyTemplate.getDudyDeptId(), dudyTemplate);
                    }
                } else if (flag < commonCount) {
                    if (returnMap.get(dudyTemplate.getDudyDeptId()) == null) {
                        returnList.add(dudyTemplate);
                        returnMap.put(dudyTemplate.getDudyDeptId(), dudyTemplate);
                    } else {
                        DudyScheduleListVO.DudyTemplate temp = returnMap.get(dudyTemplate.getDudyDeptId());
                        dudyTemplate.setSectionLevelDudyNumber(temp.getSectionLevelDudyNumber() + dudyTemplate.getSectionLevelDudyNumber());
                        returnMap.put(dudyTemplate.getDudyDeptId(), dudyTemplate);
                    }
                }
            }
            currentTemplates = dailyDudyTemplates;
            listIterator = currentTemplates.listIterator();
        }
        returnList = new ArrayList<>();
        for (String key : returnMap.keySet()) {
            returnList.add(returnMap.get(key));
        }
        if (!CollectionUtils.isEmpty(returnList)) {
            returnList = returnList.stream().sorted(Comparator.comparing(i -> i.getSort())).collect(Collectors.toList());
        }
        return returnList;
    }

    private List<DudyScheduleListVO.DudyTemplate> getHoilDayCount(List<DudyScheduleListVO.DudyTemplate> dailyDudyTemplates, Integer commonCount, List<DutyScheduleSetCustomRecord> dutyScheduleSetCustomRecords, BaseDeptInfo custom) {
        List<DudyScheduleListVO.DudyTemplate> returnList = new ArrayList<>();
        List<DudyScheduleListVO.DudyTemplate> currentTemplates = dailyDudyTemplates;
        Map<String, DudyScheduleListVO.DudyTemplate> returnMap = new HashMap<>();
        DutyScheduleSetCustomRecord currentRecord = null;
        if (!CollectionUtils.isEmpty(dutyScheduleSetCustomRecords)) {
            dutyScheduleSetCustomRecords = dutyScheduleSetCustomRecords.stream().filter(i -> DutyScheduleTypeEnum
                    .TYPE_HOILDAY.getValue().equals(i.getSType())).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(dutyScheduleSetCustomRecords)) {
                List<DutyScheduleSetCustomRecord> temp = dutyScheduleSetCustomRecords;
                if (!CollectionUtils.isEmpty(dutyScheduleSetCustomRecords)) {
                    currentTemplates = dailyDudyTemplates.stream().filter(j -> temp.stream().map(i -> i.getDeptId())
                            .collect(Collectors.toList()).contains(j.getDudyDeptId())).collect(Collectors.toList());
                }
                dutyScheduleSetCustomRecords = dutyScheduleSetCustomRecords.stream().filter(i ->
                        DutyScheduleSetCustomRecordStatusEnum.NOT_PASSED_YET.getValue().equals(i.getNeedCount())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(dutyScheduleSetCustomRecords)) {
                    currentRecord = dutyScheduleSetCustomRecords.get(0);
                }
            }
        }
        ListIterator<DudyScheduleListVO.DudyTemplate> listIterator = dailyDudyTemplates.listIterator();
        int flag = 0;
        if (currentRecord != null) {
            DutyScheduleSetCustomRecord tempCurrentRecord = currentRecord;
            DudyScheduleListVO.DudyTemplate dudyTemplate = new DudyScheduleListVO.DudyTemplate();
            BeanUtils.copyProperties(currentTemplates.stream().filter(i -> i.getDudyDeptId().equals(tempCurrentRecord.getDeptId()))
                    .collect(Collectors.toList()).get(0), dudyTemplate);
            if (dudyTemplate.getSectionLevelDudyNumber() < currentRecord.getNeedCount()) {
                flag += dudyTemplate.getSectionLevelDudyNumber();
                currentTemplates.remove(dudyTemplate);
                dudyTemplate.setSectionLevelDudyNumber(flag);
                returnList.add(dudyTemplate);
                returnMap.put(dudyTemplate.getDudyDeptId(), dudyTemplate);
            } else {
                flag += currentRecord.getNeedCount();
                currentTemplates.remove(dudyTemplate);
                dudyTemplate.setSectionLevelDudyNumber(flag);
                returnList.add(dudyTemplate);
                returnMap.put(dudyTemplate.getDudyDeptId(), dudyTemplate);
            }
            if (flag > commonCount) {
                flag = commonCount;
                dudyTemplate.setSectionLevelDudyNumber(flag);
                returnList.add(dudyTemplate);
                return returnList;
            }
        }
        if (commonCount == 0) {
            while (listIterator.hasNext()) {
                DudyScheduleListVO.DudyTemplate dudyTemplate = new DudyScheduleListVO.DudyTemplate();
                BeanUtils.copyProperties(listIterator.next(), dudyTemplate);
                dudyTemplate.setSectionLevelDudyNumber(0);
                returnList.add(dudyTemplate);
            }
            return returnList;
        }
        if (dailyDudyTemplates.stream().map(DudyScheduleListVO.DudyTemplate::getSectionLevelDudyNumber).reduce((a, b) -> a + b).orElse(0) == 0) {
            while (listIterator.hasNext()) {
                DudyScheduleListVO.DudyTemplate dudyTemplate = new DudyScheduleListVO.DudyTemplate();
                BeanUtils.copyProperties(listIterator.next(), dudyTemplate);
                dudyTemplate.setSectionLevelDudyNumber(0);
                returnList.add(dudyTemplate);
            }
            return returnList;
        }
        while (flag < commonCount) {
            while (listIterator.hasNext()) {
                DudyScheduleListVO.DudyTemplate dudyTemplate = new DudyScheduleListVO.DudyTemplate();
                BeanUtils.copyProperties(listIterator.next(), dudyTemplate);
                if (flag == commonCount) {
                    if (returnMap.get(dudyTemplate.getDudyDeptId()) == null) {
                        dudyTemplate.setSectionLevelDudyNumber(0);
                        returnList.add(dudyTemplate);
                        returnMap.put(dudyTemplate.getDudyDeptId(), dudyTemplate);
                    }
                    continue;
                }
                flag += dudyTemplate.getSectionLevelDudyNumber();
                if (flag >= commonCount) {
                    int current = dudyTemplate.getSectionLevelDudyNumber() - (flag - commonCount);
                    flag = commonCount;
                    if (returnMap.get(dudyTemplate.getDudyDeptId()) == null) {
                        dudyTemplate.setSectionLevelDudyNumber(current);
                        returnList.add(dudyTemplate);
                        returnMap.put(dudyTemplate.getDudyDeptId(), dudyTemplate);
                    } else {
                        DudyScheduleListVO.DudyTemplate temp = returnMap.get(dudyTemplate.getDudyDeptId());
                        dudyTemplate.setSectionLevelDudyNumber(temp.getSectionLevelDudyNumber() + current);
                        returnMap.put(dudyTemplate.getDudyDeptId(), dudyTemplate);
                    }
                } else if (flag < commonCount) {
                    if (returnMap.get(dudyTemplate.getDudyDeptId()) == null) {
                        returnList.add(dudyTemplate);
                        returnMap.put(dudyTemplate.getDudyDeptId(), dudyTemplate);
                    } else {
                        DudyScheduleListVO.DudyTemplate temp = returnMap.get(dudyTemplate.getDudyDeptId());
                        dudyTemplate.setSectionLevelDudyNumber(temp.getSectionLevelDudyNumber() + dudyTemplate.getSectionLevelDudyNumber());
                        returnMap.put(dudyTemplate.getDudyDeptId(), dudyTemplate);
                    }
                }
            }
            currentTemplates = dailyDudyTemplates;
            listIterator = currentTemplates.listIterator();
        }
        returnList = new ArrayList<>();
        for (String key : returnMap.keySet()) {
            returnList.add(returnMap.get(key));
        }
        if (!CollectionUtils.isEmpty(returnList)) {
            returnList = returnList.stream().sorted(Comparator.comparing(i -> i.getSort())).collect(Collectors.toList());
        }
        return returnList;
    }

    private DudyLineTemplateDTO getDailyMessage(List<BaseDeptInfo> baseDeptInfos, List<DudyScheduleListVO.DudyTemplate> dailyDudyTemplates, Integer commonCount, DutyScheduleSetCustomRecord dutyScheduleSetCustomRecords, DutyScheduleTypeEnum typeCommon) {
        List<DudyScheduleListVO.DudyTemplate> returnList = new ArrayList<>();
        List<DudyScheduleListVO.DudyTemplate> lineList = new ArrayList<>();
        List<DudyScheduleListVO.DudyTemplate> currentTemplates = new ArrayList<>();
        Map<String, DudyScheduleListVO.DudyTemplate> returnMap = new HashMap<>();
        List<DutyScheduleSetCustomRecord> currentRecord = new ArrayList<>();
        Integer round = 1;
        Map<String, String> baseDeptMap = baseDeptInfos.stream().collect(Collectors.toMap(i -> i.getId(), i -> i.getGlobalSort()));
        Long manOrder = 0l;
        if (dutyScheduleSetCustomRecords != null) {
            manOrder = Long.valueOf(baseDeptMap.get(dutyScheduleSetCustomRecords.getDeptId()));
            Integer finalRound = round;
            currentRecord = Arrays.asList(dutyScheduleSetCustomRecords);
            dailyDudyTemplates.forEach(i -> i.setRound(finalRound));

            currentTemplates.forEach(i -> i.setRound(finalRound - 1));
            Map<String, DudyScheduleListVO.DudyTemplate> dudyTemplateMap = dailyDudyTemplates
                    .stream().collect(Collectors.toMap(i -> i.getDudyDeptId(), i -> i));
            for (String dept : dudyTemplateMap.keySet()) {
                String sort = baseDeptMap.get(dept);
                Long order = 0l;
                if (StringUtils.isEmpty(sort)) {
                    continue;
                } else {
                    order = Long.valueOf(sort);
                }
                if (order > manOrder) {
//                          manOrder=order;
                    currentTemplates.add(dudyTemplateMap.get(dept));
                }
            }
            currentTemplates = currentTemplates.stream().sorted(Comparator.comparing(i -> i.getSort()))
                    .collect(Collectors.toList());
        }
        int flag = 0;
        if (!CollectionUtils.isEmpty(currentRecord) && Arrays.asList(DutyScheduleSetCustomRecordStatusEnum.NOT_PASSED_YET.getValue()
                , DutyScheduleSetCustomRecordStatusEnum.NOT_USE.getValue()).contains(dutyScheduleSetCustomRecords.getStatus())) {
            for (int a = 0; a < currentRecord.size(); a++) {
                DutyScheduleSetCustomRecord tempCurrentRecord = currentRecord.get(a);
                DudyScheduleListVO.DudyTemplate dudyTemplate = new DudyScheduleListVO.DudyTemplate();
                BeanUtils.copyProperties(dailyDudyTemplates.stream().filter(i -> i.getDudyDeptId().equals(tempCurrentRecord.getDeptId()))
                        .collect(Collectors.toList()).get(0), dudyTemplate);
                Integer addValue = 0;
                if (dudyTemplate.getSectionLevelDudyNumber() < currentRecord.get(a).getNeedCount()) {
                    addValue = dudyTemplate.getSectionLevelDudyNumber();
                    flag += addValue;
                    DutyScheduleSetCustomRecord finalCurrentRecord = currentRecord.get(a);
                    currentTemplates = currentTemplates.stream().filter(i -> !i.getDudyDeptId().equals(finalCurrentRecord.getDeptId()))
                            .collect(Collectors.toList());
                    dudyTemplate.setSectionLevelDudyNumber(dudyTemplate.getSectionLevelDudyNumber());
                    dudyTemplate.setRound(round);
                } else {
                    addValue = (int) (long) currentRecord.get(a).getNeedCount();
                    flag += addValue;
                    DutyScheduleSetCustomRecord finalCurrentRecord = currentRecord.get(a);
                    currentTemplates = currentTemplates.stream().filter(i -> !i.getDudyDeptId().equals(finalCurrentRecord.getDeptId()))
                            .collect(Collectors.toList());
                    dudyTemplate.setSectionLevelDudyNumber((int) (long) currentRecord.get(a).getNeedCount());
                    dudyTemplate.setRound(round);
                }
                if (flag >= commonCount) {
                    dudyTemplate.setRound(round - 1);
                    dudyTemplate.setSectionLevelDudyNumber(addValue - (flag - commonCount));
                    returnList.add(dudyTemplate);
                    lineList.add(dudyTemplate);
                    for (String key : returnMap.keySet()) {
                        returnList.add(returnMap.get(key));
                        lineList.add(returnMap.get(key));
                    }
                    ListIterator<DudyScheduleListVO.DudyTemplate> listIterator = dailyDudyTemplates.listIterator();
                    listIterator = dailyDudyTemplates.listIterator();
                    while (listIterator.hasNext()) {
                        DudyScheduleListVO.DudyTemplate temp = new DudyScheduleListVO.DudyTemplate();
                        BeanUtils.copyProperties(listIterator.next(), temp);
                        if (!returnList.stream().map(i -> i.getDudyDeptId()).collect(Collectors.toList()).contains(temp.getDudyDeptId())) {
                            temp.setSectionLevelDudyNumber(0);
                            returnList.add(temp);
                            lineList.add(temp);
                        }
                    }
                    DudyLineTemplateDTO dudyLineTemplateDTO = new DudyLineTemplateDTO();
                    dudyLineTemplateDTO.setLineList(returnList);
                    dudyLineTemplateDTO.setSaveList(returnList);
                    return dudyLineTemplateDTO;
                } else {
                    dudyTemplate.setRound(round);
                    returnMap.put(dudyTemplate.getDudyDeptId(), dudyTemplate);
                    lineList.add(dudyTemplate);
                }
            }
        }
        if (commonCount == 0) {
            ListIterator<DudyScheduleListVO.DudyTemplate> listIterator = dailyDudyTemplates.listIterator();
            listIterator = dailyDudyTemplates.listIterator();
            while (listIterator.hasNext()) {
                DudyScheduleListVO.DudyTemplate dudyTemplate = new DudyScheduleListVO.DudyTemplate();
                BeanUtils.copyProperties(listIterator.next(), dudyTemplate);
                dudyTemplate.setSectionLevelDudyNumber(0);
                dudyTemplate.setRound(round);
                returnList.add(dudyTemplate);
                lineList.add(dudyTemplate);
            }
            DudyLineTemplateDTO dudyLineTemplateDTO = new DudyLineTemplateDTO();
            dudyLineTemplateDTO.setLineList(returnList);
            dudyLineTemplateDTO.setSaveList(returnList);
            return dudyLineTemplateDTO;
        }
        if (dailyDudyTemplates.stream().map(DudyScheduleListVO.DudyTemplate::getSectionLevelDudyNumber).reduce((a, b) -> a + b).orElse(0) == 0) {
            ListIterator<DudyScheduleListVO.DudyTemplate> listIterator = dailyDudyTemplates.listIterator();
            listIterator = dailyDudyTemplates.listIterator();
            while (listIterator.hasNext()) {
                DudyScheduleListVO.DudyTemplate dudyTemplate = new DudyScheduleListVO.DudyTemplate();
                BeanUtils.copyProperties(listIterator.next(), dudyTemplate);
                dudyTemplate.setSectionLevelDudyNumber(0);
                dudyTemplate.setRound(round);
                returnList.add(dudyTemplate);
                lineList.add(dudyTemplate);
            }
            DudyLineTemplateDTO dudyLineTemplateDTO = new DudyLineTemplateDTO();
            dudyLineTemplateDTO.setLineList(returnList);
            dudyLineTemplateDTO.setSaveList(returnList);
            return dudyLineTemplateDTO;
        }
        while (flag < commonCount) {
            ListIterator<DudyScheduleListVO.DudyTemplate> listIterator = null;
            if (!org.apache.commons.collections4.CollectionUtils.isEmpty(currentTemplates) && currentTemplates.size() != dailyDudyTemplates.size()) {
                listIterator = currentTemplates.listIterator();
            } else {
                listIterator = dailyDudyTemplates.listIterator();
            }
            while (listIterator.hasNext()) {
                DudyScheduleListVO.DudyTemplate dudyTemplate = new DudyScheduleListVO.DudyTemplate();
                BeanUtils.copyProperties(listIterator.next(), dudyTemplate);
                dudyTemplate.setRound(round);
                if (flag == commonCount) {
                    if (returnMap.get(dudyTemplate.getDudyDeptId()) == null) {
                        dudyTemplate.setSectionLevelDudyNumber(0);
                        if (round > 1) {
                            dudyTemplate.setRound(round - 1);
                        }
                        returnList.add(dudyTemplate);
                        lineList.add(dudyTemplate);
                        returnMap.put(dudyTemplate.getDudyDeptId(), dudyTemplate);
                    }
                    continue;
                }
                flag += dudyTemplate.getSectionLevelDudyNumber();
                if (flag >= commonCount) {
                    int current = dudyTemplate.getSectionLevelDudyNumber() - (flag - commonCount);
                    flag = commonCount;
                    if (returnMap.get(dudyTemplate.getDudyDeptId()) == null) {
                        dudyTemplate.setSectionLevelDudyNumber(current);
                        returnList.add(dudyTemplate);
                        lineList.add(dudyTemplate);
                        returnMap.put(dudyTemplate.getDudyDeptId(), dudyTemplate);
                    } else {
                        DudyScheduleListVO.DudyTemplate temp = returnMap.get(dudyTemplate.getDudyDeptId());
                        DudyScheduleListVO.DudyTemplate line = new DudyScheduleListVO.DudyTemplate();
                        BeanUtils.copyProperties(dudyTemplate, line);
                        line.setSectionLevelDudyNumber(current);
                        lineList.add(line);
                        dudyTemplate.setSectionLevelDudyNumber(temp.getSectionLevelDudyNumber() + current);
                        returnMap.put(dudyTemplate.getDudyDeptId(), dudyTemplate);
                    }
                } else if (flag < commonCount) {
                    if (returnMap.get(dudyTemplate.getDudyDeptId()) == null) {
                        returnList.add(dudyTemplate);
                        DudyScheduleListVO.DudyTemplate line = new DudyScheduleListVO.DudyTemplate();
                        BeanUtils.copyProperties(dudyTemplate, line);
                        lineList.add(line);
                        returnMap.put(dudyTemplate.getDudyDeptId(), dudyTemplate);
                    } else {
                        DudyScheduleListVO.DudyTemplate temp = returnMap.get(dudyTemplate.getDudyDeptId());
                        DudyScheduleListVO.DudyTemplate line = new DudyScheduleListVO.DudyTemplate();
                        BeanUtils.copyProperties(dudyTemplate, line);
                        lineList.add(line);
                        dudyTemplate.setSectionLevelDudyNumber(temp.getSectionLevelDudyNumber() + dudyTemplate.getSectionLevelDudyNumber());
                        returnMap.put(dudyTemplate.getDudyDeptId(), dudyTemplate);
                    }
                }
            }
            round++;
            currentTemplates = dailyDudyTemplates;
        }
        returnList = new ArrayList<>();
        for (String key : returnMap.keySet()) {
            returnList.add(returnMap.get(key));
        }
        if (!CollectionUtils.isEmpty(returnList)) {
            for (DudyScheduleListVO.DudyTemplate dudyTemplate : dailyDudyTemplates) {
                if (!returnList.stream().map(DudyScheduleListVO.DudyTemplate::getDudyDeptId).collect(Collectors.toList())
                        .contains(dudyTemplate.getDudyDeptId())) {
                    DudyScheduleListVO.DudyTemplate temp = new DudyScheduleListVO.DudyTemplate();
                    BeanUtils.copyProperties(dudyTemplate, temp);
                    temp.setSectionLevelDudyNumber(0);
                    returnList.add(temp);
                }
            }
            returnList = returnList.stream().sorted(Comparator.comparing(i -> i.getSort())).collect(Collectors.toList());
        }
        DudyLineTemplateDTO dudyLineTemplateDTO = new DudyLineTemplateDTO();
//        lineList=lineList.stream().sorted(Comparator.comparing(i->i.getSort())).collect(Collectors.toList());
        dudyLineTemplateDTO.setLineList(lineList);
        dudyLineTemplateDTO.setSaveList(returnList);
        Integer maxRound = returnList.stream().map(DudyScheduleListVO.DudyTemplate::getRound).max(Comparator.comparingInt(i -> i)).orElse(1);
        Long finalManOrder = manOrder;
        returnList.forEach(i -> {
            if (Long.parseLong(i.getSort() != null ? i.getSort() : "0") < finalManOrder && i.getSectionLevelDudyNumber() == 0) {
                i.setRound(maxRound);
            }
        });
        return dudyLineTemplateDTO;
    }


    public void getChild(BaseDeptInfo baseDeptInfo, List<BaseDeptInfo> childrens, List<BaseDeptInfo> deptInfos) {
        List<BaseDeptInfo> myChildren = deptInfos.stream().filter(i -> i.getParentid() != null && i.getParentid().equals(baseDeptInfo.getId())).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(myChildren)) {
            childrens.addAll(myChildren);
            for (BaseDeptInfo child : myChildren) {
                getChild(child, childrens, deptInfos);
            }
        } else {
            return;
        }
    }

//    public static void main(String[] args) {
//        System.out.println(new BigInteger("000000000003000034000007000001000002"));
//    }
}
